(function($) {
    'use strict';

    $(document).ready(function() {
        var CredoraxFieldSelectors = {
            mode: '#woocommerce_credorax_mode',
            merchant_id: '#woocommerce_credorax_merchant_id',
            sub_merchant_id: '#woocommerce_credorax_sub_merchant_id',
            signature_key: '#woocommerce_credorax_signature_key',
            static_key: '#woocommerce_credorax_static_key',
            sandbox_merchant_id: '#woocommerce_credorax_sandbox_merchant_id',
            sandbox_sub_merchant_id: '#woocommerce_credorax_sandbox_sub_merchant_id',
            sandbox_signature_key: '#woocommerce_credorax_sandbox_signature_key',
            sandbox_static_key: '#woocommerce_credorax_sandbox_static_key',
            enable_3d_secure: '#woocommerce_credorax_enable_3d_secure',
            use_smart_3d: '#woocommerce_credorax_use_smart_3d'
        }
        var getField = function(field) {
            return $(CredoraxFieldSelectors[field]);
        };

        var getFieldVal = function(field) {
            return getField(field).length ? getField(field).val() : null;
        };

        var hideField = function(field, val) {
            return getField(field).length ? getField(field).closest('tr').hide() : false;
        };

        var showField = function(field, val) {
            return getField(field).length ? getField(field).closest('tr').show() : false;
        };

        var updateModeCredentialsFields = function() {
            if (getFieldVal('mode') === 'sandbox') {
                hideField('merchant_id');
                hideField('sub_merchant_id');
                hideField('signature_key');
                hideField('static_key');
                showField('sandbox_merchant_id');
                showField('sandbox_sub_merchant_id');
                showField('sandbox_signature_key');
                showField('sandbox_static_key');
            } else {
                showField('merchant_id');
                showField('sub_merchant_id');
                showField('signature_key');
                showField('static_key');
                hideField('sandbox_merchant_id');
                hideField('sandbox_sub_merchant_id');
                hideField('sandbox_signature_key');
                hideField('sandbox_static_key');
            }
        }

        var update3dSecureFields = function() {
            if (getFieldVal('enable_3d_secure') == 1) {
                showField('use_smart_3d');
            } else {
                hideField('use_smart_3d');
            }
        }

        $(document).on('change', CredoraxFieldSelectors.mode, updateModeCredentialsFields);
        $(document).on('change', CredoraxFieldSelectors.enable_3d_secure, update3dSecureFields);

        updateModeCredentialsFields();
        update3dSecureFields();


    });
})(jQuery);
