(function($) {
    'use strict';
    $(window).on('load', function() {

        // Login Security MFP
        function getUserDeviceDetails() {
            const userAgent = navigator.userAgent;
            let os = "Unknown";
            let osVersion = "Unknown";
            let deviceType = "Unknown";
            let languageLocale = navigator.language || "Unknown";

            // Detect OS
            if (userAgent.includes("Windows")) {
                os = "Windows";
                const versionMatch = userAgent.match(/Windows NT (\d+\.\d+)/);
                osVersion = versionMatch ? `Windows ${versionMatch[1]}` : osVersion;
            } else if (userAgent.includes("Mac OS X")) {
                os = "macOS";
                const versionMatch = userAgent.match(/Mac OS X (\d+[_\.]\d+)/);
                osVersion = versionMatch ? `macOS ${versionMatch[1].replace("_", ".")}` : osVersion;
            } else if (userAgent.includes("Android")) {
                os = "Android";
                const versionMatch = userAgent.match(/Android (\d+(\.\d+)?)/);
                osVersion = versionMatch ? versionMatch[1] : osVersion;
                deviceType = "Mobile";
            } else if (userAgent.includes("iPhone") || userAgent.includes("iPad")) {
                os = "iOS";
                const versionMatch = userAgent.match(/OS (\d+[_\.]\d+)/);
                osVersion = versionMatch ? versionMatch[1].replace("_", ".") : osVersion;
                deviceType = userAgent.includes("iPad") ? "Tablet" : "Mobile";
            }

            // Get device type
            if (/Mobi|Android/i.test(userAgent)) {
                deviceType = "Mobile";
            } else if (/Tablet|iPad/i.test(userAgent)) {
                deviceType = "Tablet";
            } else if (/Mac|Windows/i.test(userAgent)) {
                deviceType = "Desktop";
            }

            // Return all details as an object
            return {
                os,
                osVersion,
                deviceType,
                languageLocale
            };
        }

        // Get local time zone UTC+05:30
			const offsetMinutes = new Date().getTimezoneOffset();
			const sign = offsetMinutes > 0 ? "-" : "+";
			const absOffsetMinutes = Math.abs(offsetMinutes);

			const hours = Math.floor(absOffsetMinutes / 60);
			const minutes = absOffsetMinutes % 60;
			const localTimeZone = `UTC${sign}${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;

			const deviceDetails = getUserDeviceDetails();

			// Collect other details
			const screenWidth = window.screen.width;
			const screenHeight = window.screen.height;
			const platform = navigator.platform;
			const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

			// Cookies Enabled
			const cookiesEnabled = navigator.cookieEnabled ? '1' : '0';
			// JavaScript Enabled
			const javascriptEnabled = (typeof window !== 'undefined') ? '1' : '0';
			// Do Not Track Setting
			const doNotTrackSetting = (navigator.doNotTrack || navigator.msDoNotTrack || window.doNotTrack) ? '1' : '0';

			// Send the data to the PHP function using AJAX
			const dataUserInfo = {
				// screenWidth: screenWidth,
				// screenHeight: screenHeight,
				// platform: platform,
				// timezone: timezone,
				local_timezone: localTimeZone,
				os:  deviceDetails.os,
				os_version: deviceDetails.osVersion,
				device_type: deviceDetails.deviceType,
				language: deviceDetails.languageLocale,
				cookies_enabled: cookiesEnabled,
				javascript_enabled: javascriptEnabled,
				do_not_track_setting: doNotTrackSetting
			};
        // Login Security MFP END
        var passwordSectionOpened = false;
        var inputedEmail = "";

        if (typeof corsairloginData != 'undefined') {
            var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
            $('#wpaloginform').submit(function(event) {
                event.preventDefault();
                var container = $(this);
                var containerLoader = $('#corsair-login');
                var request = $(container).serialize();
                inputedEmail = $(this).find('#user_email').val();
                // if ( !$(this).find('#user_email').val() || !$(this).find('#user_password').val() ) {
                if ( !$(this).find('#user_email').val() ) {
                    Swal.fire({ type: 'error', title: 'Missing email.', text: '',allowOutsideClick: false});
                    return false;
                } else if ($(container).hasClass('working')) {
                    Swal.fire({ type: 'error', title: 'Already trying to log in. Please wait.', text: '',allowOutsideClick: false});
                    return false;
                } else {
                    $(containerLoader).block( block_config );
                    $(container).addClass('working');
                    $(container).find('input, button').prop('disabled', true);

                    // Login Security MFP
                    request += '&user_info=' + encodeURIComponent(JSON.stringify(dataUserInfo));
                    // Login Security MFP END

                    $.post(corsairloginData.ajaxUrl, request)
                    .fail(function() {
                        Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
                    })
                    .done(function(response) {
                        // Login Security MFP
                        if(response.mfpLogin == true){
                            window.location.href = corsairloginData.homeUrl;
                        }
                        // Login Security MFP END
                        if( response.pwdin ){
                            $('.password_section input').attr('disabled', false);
                            // $('.email_section input').attr('readonly', true);
                            passwordSectionOpened = true;
                            $('.password_section').slideDown();
                            $('.email_not_recognized_section').hide();
                        }else{
                            if( response.isResetRequested ){
                                Swal.fire({ type: 'success', title: response.errorMessage, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                            }else if (response.errorMessage){
                                Swal.fire({ type: 'error', title: response.errorMessage, text: '',allowOutsideClick: true}).then(function(){ /* window.location.reload(); */ });

                                /* if( response.isincorrectup ){
                                    $('.signup_user_link').parent('.password_section').hide();
                                    $('.signup_user_link').parent('.forgot_password_section').show();
                                } */

                            } else if( response.isOtpSend ){
                                $('body').find('.login_section').hide();
                                $('body').find('.otp_section').html( response.otpContent );
                                $('.signup_user_link').parent('.password_section').hide();
                                // Login Security MFP
                            }else if( response.isMfpOtpSend ){
                                $('.password_section').hide();
                                $('body').find('.login_section').hide();
                                $('body').find('.otp_section').html( response.mfpOtpContent );
                                // Login Security MFP END
                            }
                            else if (!response.isLoggedIn){
                                Swal.fire({ type: 'error', title: 'Unknown error logging in', text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                            } else {
                                // window.location.reload();
                                // Login Security MFP "&& response.infoMessage != undefined" added
                                if( response.infoMessage != "" && response.infoMessage != undefined ){
                                    Swal.fire({
                                        type: 'success',
                                        title: response.infoMessage,
                                        text: '',
                                        input: 'checkbox',
                                        inputPlaceholder: 'Do not show this message again.',
                                        allowOutsideClick: true
                                    }).then(function( result ){
                                        // window.location.href = corsairloginData.profileUrl
                                        if( typeof result.value != 'undefined' && result.value == 1 ){
                                            $(containerLoader).block( block_config );
                                            var request = {'action' : 'dont_show_profile_page_action'};
                                            $.post(corsairloginData.ajaxUrl, request)
                                            .fail(function() {
                                                //console.log('fail');
                                                window.location.href = corsairloginData.homeUrl;
                                            })
                                            .done(function(response) {
                                                window.location.href = corsairloginData.profileUrl;
                                            })
                                            .always(function(response) {
                                                //console.log('always');
                                                $(containerLoader).unblock();
                                            });
                                        }else{
                                            window.location.href = corsairloginData.profileUrl;
                                        }
                                    });
                                }else{
                                    window.location.href = corsairloginData.homeUrl;
                                }
                            }
                        }
                        $(containerLoader).unblock();
                    })
                    .always(function(response) {
                        if (!response.isLoggedIn) {
                            $(container).find('input, button').prop('disabled', false);
                            $(container).removeClass('working');
                            $(containerLoader).unblock();
                        }
                    });
                }
                return false;
            });
            // Login Security MFP
            $('body').on('click', '#resendMfp', function(){
                var queryString = window.location.search;
                if (queryString.indexOf("selectUser=yes") !== -1) {
                    var $form = $('body').find('form#wpaloginform_verify');
                }else{
                    var $form = $('body').find('form#wpaloginform');
                }
                const deviceDetailsResend = getUserDeviceDetails();

                //var request = $form.serialize() + '&resendMfpOtpAct=1';
                var request = $form.serialize() + '&resendMfpOtpAct=1&os=' + encodeURIComponent(deviceDetailsResend.os) + '&os_version=' + encodeURIComponent(deviceDetailsResend.osVersion) + '&device_type=' + encodeURIComponent(deviceDetailsResend.deviceType);
                $form.block( block_config );
                $form.addClass('working');
                $form.find('input, button').prop('disabled', true);
                $.post(corsairloginData.ajaxUrl, request)
                    .fail(function() {
                        Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
                    })
                    .done(function(response) {
                        if( response.isMfpOtpSend ){
                            $('body').find('.login_section').hide();
                            $('body').find('.otp_section').html('');
                            $('body').find('.otp_section').html( response.mfpOtpContent);
                        }else if( response.errorMessage != "" ){
                            Swal.fire({ type: 'error', title: response.errorMessage, text: '',allowOutsideClick: true}).then(function(){ /*window.location.reload();*/ });
                        }else{
                            Swal.fire({ type: 'error', title: 'Unknown error in reseting password', text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                        }
                        $form.unblock();
                    })
                    .always(function(response) {
                        $form.find('input, button').prop('disabled', false);
                        $form.removeClass('working');
                        $form.unblock();
                    });
            });
            // Login Security MFP END
            $('body').on('input', 'input[name="user_email"]', function(){
                $(this).val($(this).val().replace(/\s/g,''));
                if( passwordSectionOpened == true && inputedEmail != $(this).val() ){
                    $('.password_section').slideUp();
                    $('input[name="user_password"]').val('');
                    passwordSectionOpened = false;
                }
            });

            $('body').on('click', '.switch-method', function(e){
                $('body').find('form#wpaloginform #switch_method').remove();
                $('<input>').attr({type: 'hidden',id: 'switch_method',name: 'switch_method', value: $(this).attr('data-type')}).appendTo('form#wpaloginform');
                $('body').find('section.otp_section').html('');
                const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
                for (let i = 1; i < interval_id; i++) {
                    window.clearInterval(i);
                }
                $('form#wpaloginform').submit();
            });

            $('body').on('click', '#resend', function(){
                var $form = $('body').find('form#wpaloginform');
                var request = $form.serialize() + '&resendOtpAct=1';
                $form.block( block_config );
                $form.addClass('working');
                $form.find('input, button').prop('disabled', true);
                $.post(corsairloginData.ajaxUrl, request)
                    .fail(function() {
                        Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
                    })
                    .done(function(response) {
                        if( response.isOtpSend ){
                            $('body').find('.login_section').hide();
                            $('body').find('.otp_section').html('');
                            $('body').find('.otp_section').html( response.otpContent );
                        }else if( response.errorMessage != "" ){
                            Swal.fire({ type: 'error', title: response.errorMessage, text: '',allowOutsideClick: true}).then(function(){ /*window.location.reload();*/ });
                        }else{
                            Swal.fire({ type: 'error', title: 'Unknown error in reseting password', text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                        }
                        $form.unblock();
                    })
                    .always(function(response) {
                        $form.find('input, button').prop('disabled', false);
                        $form.removeClass('working');
                        $form.unblock();
                    });
            });
            $('#wparesetpwdform').submit(function(event) {
                event.preventDefault();
                var container = $(this);
                var request = $(container).serialize();
                if ( !$(this).find('#user_email').val() ) {
                    Swal.fire({ type: 'error', title: 'Email address is required.', text: '',allowOutsideClick: false});
                    return false;
                } else if ($(container).hasClass('working')) {
                    Swal.fire({ type: 'error', title: 'Already trying to send request. Please wait.', text: '',allowOutsideClick: false});
                    return false;
                } else {
                    $(container).block( block_config );
                    $(container).addClass('working');
                    $(container).find('input, button').prop('disabled', true);


                    $.post(corsairloginData.ajaxUrl, request)
                    .fail(function() {
                        Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
                    })
                    .done(function(response) {
                        if( response.isResetRequested ){
                            Swal.fire({ type: 'success', title: response.errorMessage, text: '',allowOutsideClick: true}).then(function(){ window.location.href = corsairloginData.homeUrl; });
                        }else if (response.errorMessage) {
                            Swal.fire({ type: 'error', title: response.errorMessage, text: '',allowOutsideClick: true}).then(function(){ /* window.location.reload(); */ });
                        } else {
                            Swal.fire({ type: 'error', title: 'Unknown error in reset request', text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                        }
                        $(container).unblock();
                    })
                    .always(function(response) {
                        if (!response.isResetRequested) {
                            $(container).find('input, button').prop('disabled', false);
                            $(container).removeClass('working');
                            $(container).unblock();
                        }
                    });
                }
                return false;
            });
            $('#wparesetpassform').submit(function(event) {
                event.preventDefault();
                var container = $(this);
                var request = $(container).serialize();
                if ( !$(this).find('#pass1').val() ) {
                    Swal.fire({ type: 'error', title: 'New password required.', text: '',allowOutsideClick: false});
                    return false;
                }else if ( !$(this).find('#pass2').val() ) {
                    Swal.fire({ type: 'error', title: 'Confirm new password required.', text: '',allowOutsideClick: false});
                    return false;
                }else if ( $(this).find('#pass1').val() != $(this).find('#pass2').val() ) {
                    Swal.fire({ type: 'error', title: 'Passwords don\'t match.', text: '',allowOutsideClick: false});
                    return false;
                } else if ($(container).hasClass('working')) {
                    Swal.fire({ type: 'error', title: 'Already trying to send request. Please wait.', text: '',allowOutsideClick: false});
                    return false;
                } else {
                    $(container).block( block_config );
                    $(container).addClass('working');
                    $(container).find('input, button').prop('disabled', true);

                    $.post(corsairloginData.ajaxUrl, request)
                    .fail(function() {
                        Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){window.location.reload();});
                    })
                    .done(function(response) {
                        if( response.isReset ){
                            Swal.fire({ type: 'success', title: response.errorMessage, text: '',allowOutsideClick: true}).then(function(){ window.location.href = corsairloginData.homeUrl; });
                        }else if (response.errorMessage) {
                            Swal.fire({ type: 'error', title: response.errorMessage, text: '',allowOutsideClick: true}).then(function(){ /* window.location.reload(); */ });
                        } else {
                            Swal.fire({ type: 'error', title: 'Unknown error in reseting password.', text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                        }
                        $(container).unblock();
                    })
                    .always(function(response) {
                        if (!response.isReset) {
                            $(container).find('input, button').prop('disabled', false);
                            $(container).removeClass('working');
                            $(container).unblock();
                        }
                    });
                }
                return false;
            });

            $('body').on('change', 'input[name="opt_email_login"]', function(event){
                event.preventDefault();
                console.log( $(this).is(':checked') );
                var $this = $(this);
                const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
                for (let i = 1; i < interval_id; i++) {
                    window.clearInterval(i);
                }
                if( $(this).is(':checked') ){ //enable OTP email for login

                    $this.prop( "checked", false );

                    var container = $('.2fa_otp_section');
                    var request = {'action' : 'sendOtpForActivatingAct'};
                    $(container).block( block_config );
                    $(container).addClass('working');
                    $(container).find('input, button').prop('disabled', true);

                    $.post(corsairloginData.ajaxUrl, request)
                    .fail(function() {
                        Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
                    })
                    .done(function(response) {
                        if( response.error == 0 && response.html != "" ){
                            $('#enableOTP2faModal').find('.modal-body').html( response.html );
                            $("#enableOTP2faModal").modal({backdrop: 'static', keyboard: false},'show');
                        }else{
                            Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                        }
                        $(container).unblock();
                    })
                    .always(function(response) {
                        if (!response.isReset) {
                            $(container).find('input, button').prop('disabled', false);
                            $(container).removeClass('working');
                            $(container).unblock();
                        }
                    });
                }else{ //disable OTP email for login

                    $this.prop( "checked", true );

                    var container = $('.2fa_otp_section');
                    var request = {'action' : 'sendOtpForDeActivatingAct'};
                    $(container).block( block_config );
                    $(container).addClass('working');
                    $(container).find('input, button').prop('disabled', true);

                    $.post(corsairloginData.ajaxUrl, request)
                    .fail(function() {
                        Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
                    })
                    .done(function(response) {
                        if( response.error == 0 && response.html != "" ){
                            $('#disableOTP2faModal').find('.modal-body').html( response.html );
                            $("#disableOTP2faModal").modal({backdrop: 'static', keyboard: false},'show');
                        }else{
                            Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                        }
                        $(container).unblock();
                    })
                    .always(function(response) {
                        if (!response.isReset) {
                            $(container).find('input, button').prop('disabled', false);
                            $(container).removeClass('working');
                            $(container).unblock();
                        }
                    });
                }
                return false;
            });

            /* $('#enable_otp2fa_modal').on('click', function(event) {
                event.preventDefault();

                const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
                for (let i = 1; i < interval_id; i++) {
                    window.clearInterval(i);
                }

                var container = $('.2fa_otp_section');
                var request = {'action' : 'sendOtpForActivatingAct'};
                $(container).block( block_config );
                $(container).addClass('working');
                $(container).find('input, button').prop('disabled', true);

                $.post(corsairloginData.ajaxUrl, request)
                .fail(function() {
                    Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
                })
                .done(function(response) {
                    if( response.error == 0 && response.html != "" ){
                        $('#enableOTP2faModal').find('.modal-body').html( response.html );
                        $("#enableOTP2faModal").modal({backdrop: 'static', keyboard: false},'show');
                    }else{
                        Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                    }
                    $(container).unblock();
                })
                .always(function(response) {
                    if (!response.isReset) {
                        $(container).find('input, button').prop('disabled', false);
                        $(container).removeClass('working');
                        $(container).unblock();
                    }
                });
                return false;
            }); */

            $('body').on('submit', 'form[name="otp2faEnableFrm"]', function(event) {
                event.preventDefault();

                if( $(this).find('#verify-code').val() == "" ){
                    Swal.fire({ type: 'error', title: 'Please enter OTP', text: '',allowOutsideClick: true}).then(function(){ });
                    return false;
                }

                let form = $('form[name="otp2faEnableFrm"');
                let formData = $('form[name="otp2faEnableFrm"]')[0];
                let request = new FormData(formData);

                $(form).block( block_config );
                $(form).addClass('working');
                $(form).find('input, button').prop('disabled', true);

                $.ajax({
                    url: corsairloginData.ajaxUrl,
                    type: "POST",
                    data: request,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        if( response.error == 0 ){
                            Swal.fire({ type: 'success', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                            $("#enableOTP2faModal").modal('hide');
                            $('#opt_email_login').prop( "checked", true );
                        }else{
                            Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                        }
                        $(form).find('input, button').prop('disabled', false);
                        $(form).removeClass('working');
                        $(form).unblock();
                    }
                });
                return false;
            });

            /* $('#disable_otp2fa_modal').on('click', function(event) {
                event.preventDefault();
                const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
                for (let i = 1; i < interval_id; i++) {
                    window.clearInterval(i);
                }
                var container = $('.2fa_otp_section');
                var request = {'action' : 'sendOtpForDeActivatingAct'};
                $(container).block( block_config );
                $(container).addClass('working');
                $(container).find('input, button').prop('disabled', true);

                $.post(corsairloginData.ajaxUrl, request)
                .fail(function() {
                    Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
                })
                .done(function(response) {
                    if( response.error == 0 && response.html != "" ){
                        $('#disableOTP2faModal').find('.modal-body').html( response.html );
                        $("#disableOTP2faModal").modal({backdrop: 'static', keyboard: false},'show');
                    }else{
                        Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                    }
                    $(container).unblock();
                })
                .always(function(response) {
                    if (!response.isReset) {
                        $(container).find('input, button').prop('disabled', false);
                        $(container).removeClass('working');
                        $(container).unblock();
                    }
                });
                return false;
            }); */

            $('body').on('submit', 'form[name="otp2faDisableFrm"]', function(event) {
                event.preventDefault();

                if( $(this).find('#verify-code').val() == "" ){
                    Swal.fire({ type: 'error', title: 'Please enter OTP', text: '',allowOutsideClick: true}).then(function(){ });
                    return false;
                }

                let form = $('form[name="otp2faDisableFrm"');
                let formData = $('form[name="otp2faDisableFrm"]')[0];
                let request = new FormData(formData);

                $(form).block( block_config );
                $(form).addClass('working');
                $(form).find('input, button').prop('disabled', true);

                $.ajax({
                    url: corsairloginData.ajaxUrl,
                    type: "POST",
                    data: request,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        if( response.error == 0 ){
                            Swal.fire({ type: 'success', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                            $("#disableOTP2faModal").modal('hide');
                            $('#opt_email_login').prop( "checked", false );
                        }else{
                            Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                        }
                        $(form).find('input, button').prop('disabled', false);
                        $(form).removeClass('working');
                        $(form).unblock();
                    }
                });
                return false;
            });

            $('body').on('click', '#cl_member_users_list .disable2faauth', function(){
                var data = corsairloginData.actionResetAuth;
                var thisLabel = $(this).attr('data-pop-title');
                data['thisid'] = $(this).attr('data-id');
                data['thistype'] = $(this).attr('data-type');
                var current_tr = $(this).closest('tr');
                Swal({
                  title: 'Are you sure?',
                  text: "Do you want to " + thisLabel + "?",
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonText: 'Yes'
                }).then((result) => {
                  if (result.value) {
                    current_tr.block( block_config );
                    jQuery.ajax({
                        type: "post",
                        data: data,
                        cache: false,
                        url: corsairloginData.ajaxUrl,
                        success: function(response){
                            var obj = JSON.parse( response );
                            if( obj.error == 0 ){
                                window.location.reload();
                            }else{
                                Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
                            }
                            current_tr.unblock();
                        }
                    });
                  }
                });
                return false;
            });

            $('body').on('click', '#cl_member_users_list .pwdreset', function(){
                var data = corsairloginData.actionResetPwd;
                data['thisid'] = $(this).attr('data-id');
                data['thistype'] = $(this).attr('data-type');
                var current_tr = $(this).closest('tr');
                Swal({
                  title: 'Are you sure?',
                  text: "Do you want to send reset password link?",
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonText: 'Yes'
                }).then((result) => {
                    if (result.value) {
                        current_tr.block( block_config );
                        jQuery.ajax({
                            type: "post",
                            data: data,
                            cache: false,
                            url: corsairloginData.ajaxUrl,
                            success: function(response){
                                var obj = JSON.parse( response );
                                if( obj.error == 0 ){
                                    Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                                }else{
                                    Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
                                }
                                current_tr.unblock();
                            }
                        });
                    }
                });
                return false;
            });

            $('body').on('change', '#cl_member_users_list .toggleloginsection input[type="checkbox"]', function(){

                var toggleLogin = '0';
                if( $(this).is(':checked') ){
                    toggleLogin = '1';
                }
                var thisElem = $(this);
                var data = corsairloginData.actionToggleLogin;
                data['thisid'] = $(this).val();
                data['togglelogin'] = toggleLogin;
                var current_tr = $(this).closest('tr');

                current_tr.block( block_config );
                jQuery.ajax({
                    type: "post",
                    data: data,
                    cache: false,
                    url: corsairloginData.ajaxUrl,
                    success: function(response){
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
                            // window.location.reload();
                            // Swal.fire({ type: 'success', title: obj.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                            thisElem.next('label').text( obj.statusLabel );
                        }else{
                            Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
                        }
                        current_tr.unblock();
                    }
                });
                return false;
            });

            $('body').on('change', '#cl_member_users_list .togglewithdrawalsection input[type="checkbox"]', function(){

                var toggleWithdrawal = '1';
                if( $(this).is(':checked') ){
                    toggleWithdrawal = '0';
                }
                var thisElem = $(this);
                var data = corsairloginData.actionToggleWithdrawal;
                data['thisid'] = $(this).val();
                data['togglewithdrawal'] = toggleWithdrawal;
                var current_tr = $(this).closest('tr');

                current_tr.block( block_config );
                jQuery.ajax({
                    type: "post",
                    data: data,
                    cache: false,
                    url: corsairloginData.ajaxUrl,
                    success: function(response){
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
                            thisElem.next('label').text( obj.statusLabel );
                        }else{
                            Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: true});
                        }
                        current_tr.unblock();
                    }
                });
                return false;
            });
         }

        //236 switch user - switch login form
        $('#wpaloginform_switch').submit(function(event) {
            event.preventDefault();
            var email = $('#user_email').val();
            var nonce = $('#nonce').val();
            if(email == ''){
                swalToast({ type: 'error', title: "Please add email" });
            }else{
                $('#user_to_switch').val(email);
                $('#user_to_switch_nonce').val(nonce);
                $('#user_switch_2fa').modal('show')
            }

        });
        //236 switch user - 2FA code validation
        $('#user_ga_otp').on('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
        //236 switch user - Member detail table switch button
        $('body').on('click', '.switchUser', function(){
            var email = $(this).data('email');
            var nonce = $(this).data('nonce');
            $('#user_to_switch').val(email);
            $('#user_to_switch_nonce').val(nonce);
            $('#user_switch_2fa').modal('show')

        });
        //236 switch user - 2FA form submit
        $('#user_switch_2fa_form').submit(function(event) {
            event.preventDefault();
            var email = $('#user_to_switch').val();
            var authCode = $('#user_ga_otp').val();
            var micro = $('body').find('#user_switch_2fa_form input[name="_micro"]').val();
            var nonce = $('body').find('#user_switch_2fa_form #user_to_switch_nonce').val();
            var container = $('.switch_user_2fa_loader');
            $(container).block( block_config );
            $.ajax({
                url: corsairloginData.ajaxUrl,
                type: "POST",
                data: { action: "cip_user_switch_2fa", '_micro' : micro, 'email' : email, 'authCode' : authCode, 'nonce' : nonce },
                success: async function (response) {
                    var obj = JSON.parse( response );

                    if( obj.error == 0 && obj.auth_verified == true){
                        var siteUrl = window.location.origin;
                        var newUrl = siteUrl + "/content/csr-portal/dashboard/csr-central-dashboard/";
                        window.location.href = newUrl;
                        //$('#user_switch_2fa').modal('hide')

                    }
                    if( obj.error == 1 ){
                        swalToast({ type: 'error', title: obj.msg });
                    }
                    console.log(obj.msg)
                    if( obj.msg != 'Invalid authenticator code' ){

                        $('#user_switch_2fa').modal('hide')
                        $(container).unblock();
                    }else{
                        $(container).unblock();

                    }
                },
                error: function () {
                    //$('#user_switch_2fa').modal('hide')
                    Swal.fire({ type: 'error', title: 'An error was encountered', text: '',allowOutsideClick: false});
                    $(container).unblock();
                }
            });
        });

       $('body').on('change', 'input[name="ga2fa_login"]', function(event){
            event.preventDefault();
            console.log( $(this).is(':checked') );
            var $this = $(this);
            if( $(this).is(':checked') ){ //enable GA for login
                $this.prop( "checked", false );

                var container = $('.2fa_ga_section');
                var request = {'action' : 'check_for_user_ga_twofa', 'thisType':'login'};
                $(container).block( block_config );
                $(container).addClass('working');
                $(container).find('input, button').prop('disabled', true);

                $.post(corsairloginData.ajaxUrl, request)
                .fail(function() {
                    Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
                })
                .done(function(response) {
                    if( response.error == 0 ){
                        if( response.isopen == 1 ){
                            $('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'login'}).appendTo('form[name="ga2faEnableFrm"]');
                            $("#enableGa2faModal").modal('show');
                        }else{
                            $this.prop( "checked", true );
                        }
                    }else{
                        Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                    }
                    $(container).unblock();
                })
                .always(function(response) {
                    if (!response.isReset) {
                        $(container).find('input, button').prop('disabled', false);
                        $(container).removeClass('working');
                        $(container).unblock();
                    }
                });

            }else{ //disable GA for login
                $this.prop( "checked", true );
                $('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'login'}).appendTo('form[name="ga2faDisableToggleFrm"]');
                $("#disableToggleGa2faModal").modal('show');
            }
            return false;
        });

        $('body').on('submit', 'form[name="ga2faDisableToggleFrm"]', function(event) {

            if( $(this).find('input[name="code"]').val() == "" ){
                Swal.fire({ type: 'error', title: 'Please enter 6-digit google authenticator code.', text: '',allowOutsideClick: true}).then(function(){ });
                return false;
            }

            var container = $(this);
            var request = $(this).serialize();
            $(container).block( block_config );
            $(container).addClass('working');
            $(container).find('input, button').prop('disabled', true);

            $.post(corsairloginData.ajaxUrl, request)
            .fail(function() {
                Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
            })
            .done(function(response) {
                if( response.error == 0 ){
                    if( response.thisType == 'login' ){
                        $('#ga2fa_login').prop( "checked", false );
                    }else if( response.thisType == 'withdrawal' ){
                        $('#ga2fa_withdrawal').prop( "checked", false );
                    }
                    $("#disableToggleGa2faModal").modal('hide');
                    Swal.fire({ type: 'success', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                }else{
                    Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                }
                $(container).unblock();
            })
            .always(function(response) {
                if (!response.isReset) {
                    $(container).find('input, button').prop('disabled', false);
                    $(container).removeClass('working');
                    $(container).unblock();
                }
            });
            return false;
        });
        $("#disableToggleGa2faModal").on('hide.bs.modal', function () {
            $('#disableToggleGa2faModal #thisType').remove();
            $('#disableToggleGa2faModal form')[0].reset();
        });

       $('body').on('change', 'input[name="ga2fa_withdrawal"]', function(event){
            event.preventDefault();
            console.log( $(this).is(':checked') );
            var $this = $(this);
            if( $(this).is(':checked') ){ //enable GA for withdrawal
                $this.prop( "checked", false );

                var container = $('.2fa_ga_section');
                var request = {'action' : 'check_for_user_ga_twofa', 'thisType':'withdrawal'};
                $(container).block( block_config );
                $(container).addClass('working');
                $(container).find('input, button').prop('disabled', true);

                $.post(corsairloginData.ajaxUrl, request)
                .fail(function() {
                    Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
                })
                .done(function(response) {
                    if( response.error == 0 ){
                        if( response.isopen == 1 ){
                            $('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'withdrawal'}).appendTo('form[name="ga2faEnableFrm"]');
                            $("#enableGa2faModal").modal('show');
                        }else{
                            $this.prop( "checked", true );
                        }
                    }else{
                        Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                    }
                    $(container).unblock();
                })
                .always(function(response) {
                    if (!response.isReset) {
                        $(container).find('input, button').prop('disabled', false);
                        $(container).removeClass('working');
                        $(container).unblock();
                    }
                });

            }else{ //disable GA form withdrawal
                $this.prop( "checked", true );
                $('<input>').attr({type: 'hidden',id: 'thisType',name: 'thisType', value: 'withdrawal'}).appendTo('form[name="ga2faDisableToggleFrm"]');
                $("#disableToggleGa2faModal").modal('show');
            }
            return false;
        });
        $("#enableGa2faModal").on('hide.bs.modal', function () {
            $('#enableGa2faModal #thisType').remove();
        });

       if( $('.ga2faEnableFrm').length > 0 ){

        var current_fs_g2fa, next_fs_g2fa, previous_fs_g2fa; //fieldsets
		var opacity_g2fa;
		var current_g2fa = 1;
		var steps_g2fa = $('body').find(".ga2faEnableFrm fieldset").length;
        setProgressBarGa(current_g2fa);

		// $form = $('.ga2faEnableFrm');
		$('body').on("click",".next_ga", function(event){
			var this_next = $(this);
			current_fs_g2fa = $(this).closest('fieldset');
			next_fs_g2fa = $(this).closest('fieldset').next();
			// console.log( current );

			var $form = $('body').find('.ga2faEnableFrm');
			if( current_g2fa == 3 ){
                google2Fa(event,'google2fa');
			}else{
				$(".ga2faEnableFrm #progressbar li").eq( $(".ga2faEnableFrm fieldset").index(next_fs_g2fa) ).addClass("active");
				next_fs_g2fa.show();
				current_fs_g2fa.animate({opacity: 0}, {
					step: function(now) {
						opacity_g2fa = 1 - now;

						current_fs_g2fa.css({
							'display': 'none',
							'position': 'relative'
						});
						next_fs_g2fa.css({'opacity': opacity_g2fa});
					},
					duration: 500
				});
				setProgressBarGa(++current_g2fa);
			}
		});

		$('body').on("click",".previous_ga", function(){
			current_fs_g2fa = $(this).closest('fieldset');
			previous_fs_g2fa = $(this).closest('fieldset').prev();
			// console.log( current );

			$(".ga2faEnableFrm #progressbar li").eq($(".ga2faEnableFrm fieldset").index(current_fs_g2fa)).removeClass("active");

			previous_fs_g2fa.show();

			current_fs_g2fa.animate({opacity: 0}, {
				step: function(now) {
					opacity_g2fa = 1 - now;

					current_fs_g2fa.css({
					'display': 'none',
					'position': 'relative'
					});
					previous_fs_g2fa.css({'opacity': opacity_g2fa});
				},
				duration: 500
			});
			setProgressBarGa(--current_g2fa);
		});

		function setProgressBarGa(curStep){
			var percent = parseFloat(100 / steps_g2fa) * curStep;
			percent = percent.toFixed();
			$('body').find(".ga2faEnableFrm .progress-bar").css("width",percent+"%")
		}

	}

    function google2Fa(event, fid) {
        event.preventDefault();
        if (fid == "google2fa") {
            if ($('#google_auth_key').val() != $('#backupkey').val()) {
                Swal.fire({ type: 'error', title: 'Please enter valid backup key to continue.', text: '',allowOutsideClick: true}).then(function(){ });
                return false;
            }
        }


        let form = $('form[name="ga2faEnableFrm"');
        let formData = $('form[name="ga2faEnableFrm"]')[0];
        let request = new FormData(formData);

        $(form).block( block_config );
        $(form).addClass('working');
        $(form).find('input, button').prop('disabled', true);


        $.ajax({
            url: corsairloginData.ajaxUrl,
            type: "POST",
            data: request,
            processData: false,
            contentType: false,
            success: function (response) {
                //var obj = JSON.parse( response );
                if( response.error == 0 ){
                    Swal.fire({ type: 'success', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });

                    if( response.thisType == 'login' ){
                        $('#ga2fa_login').prop( "checked", true );
                    }else if( response.thisType == 'withdrawal' ){
                        $('#ga2fa_withdrawal').prop( "checked", true );
                    }
                    $("#enableGa2faModal").modal('hide');
                }else{
                    Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                }
                $(form).find('input, button').prop('disabled', false);
                $(form).removeClass('working');
                $(form).unblock();
            }
        });
        return false;

    }

    $('form[name="ga2faDisableFrm"]').submit(function(event) {

        if( $(this).find('input[name="code"]').val() == "" ){
            Swal.fire({ type: 'error', title: 'Please enter 6-digit google authenticator code.', text: '',allowOutsideClick: true}).then(function(){ });
            return false;
        }

        let form = $('form[name="ga2faDisableFrm"');
        let formData = $('form[name="ga2faDisableFrm"]')[0];
        let request = new FormData(formData);

        $(form).block( block_config );
        $(form).addClass('working');
        $(form).find('input, button').prop('disabled', true);

        $.ajax({
            url: corsairloginData.ajaxUrl,
            type: "POST",
            data: request,
            processData: false,
            contentType: false,
            success: function (response) {
                if( response.error == 0 ){
                    Swal.fire({ type: 'success', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ window.location.reload(); });
                    $("#disableGa2faModal").modal('hide');
                }else{
                    Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
                }
                $(form).find('input, button').prop('disabled', false);
                $(form).removeClass('working');
                $(form).unblock();
            }
        });
        return false;
    });

    $("#show_hide_password a").on('click', function(event) {
        event.preventDefault();
        if($('#show_hide_password input').attr("type") == "text"){
            $('#show_hide_password input').attr('type', 'password');
            $('#show_hide_password i').addClass( "fa-eye-slash" );
            $('#show_hide_password i').removeClass( "fa-eye" );
        }else if($('#show_hide_password input').attr("type") == "password"){
            $('#show_hide_password input').attr('type', 'text');
            $('#show_hide_password i').removeClass( "fa-eye-slash" );
            $('#show_hide_password i').addClass( "fa-eye" );
        }
    });

    $(".toggle_password a").on('click', function(event) {
        event.preventDefault();
        var thisToggleElem = $(this).parent().parent('.toggle_password');
        if(thisToggleElem.find('input').attr("type") == "text"){
            thisToggleElem.find('input').attr('type', 'password');
            thisToggleElem.find('i').addClass( "fa-eye-slash" );
            thisToggleElem.find('i').removeClass( "fa-eye" );
        }else if( thisToggleElem.find('input').attr("type") == "password"){
            thisToggleElem.find('input').attr('type', 'text');
            thisToggleElem.find('i').removeClass( "fa-eye-slash" );
            thisToggleElem.find('i').addClass( "fa-eye" );
        }
    });

    $('body').on('click', '#getnewcode', function(event){
        event.preventDefault();
        $('.resend_response').html('');
        if( $(this).hasClass('getnewcodedisable') ){
            var container = $('body').find('form.otp2faDisableFrm');
            var request = {'action' : 'sendOtpForDeActivatingAct','resendOtpAct' : 1 };
        }else{
            var container = $('body').find('form.otp2faEnableFrm');
            var request = {'action' : 'sendOtpForActivatingAct','resendOtpAct' : 1 };
        }
        $(container).block( block_config );
        $(container).addClass('working');
        $(container).find('input, button').prop('disabled', true);

        $.post(corsairloginData.ajaxUrl, request)
        .fail(function() {
            Swal.fire({ type: 'error', title: 'Something went wrong. Please try again.', text: '',allowOutsideClick: true}).then(function(){ });
        })
        .done(function(response) {
            if( response.error == 0 ){
                $('body').find('#getnewcode').addClass('disabled').attr('disabled', true).attr('data-stat', 'countdown');
                $('.resend_response').html( response.msg );
                setTimeout(() => {
                    var is_countdown_resend = $('body').find('#getnewcode').attr('data-stat') == 'countdown';
                    if(is_countdown_resend){
                        var sec = parseInt('60');
                        var countdown = setInterval(() => {
                            if(sec > 0){
                                sec--;
                                $('#getnewcode').text("Resend in "+(sec)+'s')
                            }else{
                                $('#getnewcode').attr('data-stat','').removeClass('disabled').attr('disabled', false).text('Resend OTP')
                                clearInterval(countdown)
                            }
                        }, 1000);
                    }
                }, 1);

            }else{
                Swal.fire({ type: 'error', title: response.msg, text: '',allowOutsideClick: true}).then(function(){ });
            }
            $(container).unblock();
        })
        .always(function(response) {
            $(container).find('input, button').prop('disabled', false);
            $(container).removeClass('working');
            $(container).unblock();
        });
        return false;
    });

    });

    if( corsairloginData.isLoggedInUser == "1" && corsairloginData.isAdminLoggedIn != "1" ){
        var timeoutTracker;
        var interval;
        resetTimer();
        $(document).on('mousemove touchstart click keydown scroll',document,function(e){
            resetTimer();
            // activity found
        });
        function resetTimer(){
            if( timeoutTracker ){
                clearTimeout(timeoutTracker)
            }
            timeoutTracker = setTimeout(() => {
                localStorage.setItem("_expiredTime", Date.now() + parseInt( corsairloginData.idleLogoutTime ));
            }, 300);
            // reset timer run
        }
        interval = setInterval(() => {

            if( localStorage.getItem('_expiredTime') !== null ){
                const expiredTime = parseInt( localStorage.getItem("_expiredTime") || 0, 10 );
                // console.log( 'expiredTime', expiredTime - Date.now() );
                if (expiredTime < Date.now()) {
                    localStorage.removeItem("_expiredTime");
                    clearInterval( interval );
                    idleLogout();
                }
            }else{
                localStorage.setItem("_expiredTime", Date.now() + parseInt( corsairloginData.idleLogoutTime ));
            }

        }, 1000);
        function idleLogout(){
            // logout called
            var request = {'action' : 'idle_inactivity_logout_act'};
            $.post(corsairloginData.ajaxUrl, request)
            .fail(function() {
                //failed called
                localStorage.removeItem("_expiredTime");
                clearInterval( interval );
                window.location.href = corsairloginData.homeUrl;
            })
            .done(function(response) {
                localStorage.removeItem("_expiredTime");
                clearInterval( interval );
                window.location.href = corsairloginData.homeUrl;
            });
        }
    }else{
        localStorage.removeItem("_expiredTime");
        clearInterval( interval );
    }

 })(jQuery);