require([
    'jquery',
    'mage/url',
    'mage/translate',
    'domReady!'
], function ($, url) {
    $(window).load(function() {
        var jQuery = $;
        var userID = uuid();
        var sibsBearerTokenAuthenticationSBO = null;
        var magento_base_url = getBaseUrl();

        url.setBaseUrl(magento_base_url)

        var automaticSBOHTML = '<td colspan="4"> \
                <div id="wizard-radio-config"> \
                    <!-- Generate Data through jquery --> \
                </div> \
                <div id="wizard-config" > \
                    <!-- Generate Data through jquery --> \
                </div> \
                <div class="lds-ring"> \
                    <div></div> \
                    <div></div> \
                    <div></div> \
                    <div></div> \
                </div> \
            </td>';

        var wizardConfig = '<div id="wizard" class="wizard"> \
                <h3>' + $.mage.__('Login') + '</h3> \
                <section> \
                    <!-- Generate Data through jquery --> \
                </section> \
                <h3>' + $.mage.__('Configure Terminal') + '</h3> \
                <section> \
                    <!-- Generate Data through jquery --> \
                </section> \
                <h3>' + $.mage.__('Webhooks') + '</h3> \
                <section> \
                    <!-- Generate Data through jquery --> \
                </section> \
            </div>'

        var wizardRadioConfiguration = '<div class="toggle"> \
                <input type="radio" name="sibsConfigurationRadio" value="Manually" id="sizeDimensions" checked="checked" /> \
                <label for="sizeDimensions">' + $.mage.__('Manual Configuration') + '</label> \
                <input type="radio" name="sibsConfigurationRadio" value="Automatic" id="sizeWeight" /> \
                <label for="sizeWeight">' + $.mage.__('Automatic Configuration') + '</label> \
            </div>';

        var wizardP0HTML = '<div id="divLoginSibs"> \
                <p> \
                    <h3>' + $.mage.__('Log in to SBO SIBS') + '</h3> \
                </p> \
                <form id="formLoginSibs"> \
                    <div class="div-fields-content"> \
                        <p class="p-fields-content-right"> \
                            <label for="loginSibs">' + $.mage.__('Email') + ':</label> \
                            <input type="text" value="" placeholder="' + $.mage.__('Type your email') + '" id="loginSibs"> \
                            <label id="errorLoginSibs" class="error"> \
                            </label> \
                        </p> \
                        <p class="p-fields-content-left"> \
                            <label for="passwordSibs">' + $.mage.__('Password') + ':</label> \
                            <input type="password" value="" placeholder="' + $.mage.__('Enter your password') + '" id="passwordSibs"> \
                            <label id="errorPassSibs" class="error"></label> \
                        </p> \
                    </div> \
                    <div class="div-fields-content"> \
                        <p class="p-fields-content-right"> \
                            <label for="fenvironment">' + $.mage.__('SIBS Environment') + ':</label> \
                            <select name="fenvironment" id="fenvironment"> \
                                <option value="DEV">DEV</option> \
                                <option value="TST">TST</option> \
                                <option value="CER">CER</option> \
                                <option value="QLY">QLY</option> \
                                <option value="LIVE">LIVE</option> \
                            </select> \
                        </p> \
                    </div> \
                    <div class="div-fields-content"> \
                        <p class="p-fields-content-right"> \
                            <button type="button" id="firstLoginSibs">' + $.mage.__('Login') + '</button> \
                        </p> \
                    </div> \
                </form> \
            </div> \
            <div id="activateLoginSibs"> \
                <p> \
                ' + $.mage.__('Enter the activation code you received via SMS') + ' \
                </p> \
                <form id="formActvateLoginSibs"> \
                    <div class="div-fields-content"> \
                        <p class="p-fields-content-right"> \
                            <label for="activationCode">' + $.mage.__('Activation Code') + ':</label> \
                            <input type="text" value="" placeholder="' + $.mage.__('Enter your activation code') + '" id="activationCode"> \
                            <label id="errorActivationCode" class="error"></label> \
                        </p> \
                    </div> \
                    <div class="div-fields-content"> \
                        <p class="p-fields-content-right"> \
                            <button type="button" id="secondLoginSibs"> \
                                ' + $.mage.__('Confirm') + ' \
                            </button> \
                            <button type="button" id="requestNewcode" class="whiteButton"> \
                                ' + $.mage.__('Request new code') + ' \
                            </button> \
                        </p> \
                    </div> \
                </form> \
            </div>';

        var wizardP1HTML = '<div id="setTerminalSibs"> \
                <p> \
                    <h3> \
                        ' + $.mage.__('Select the Terminal you want to configure') + ' \
                    </h3> \
                </p> \
                <div class="div-fields-content"> \
                    <p class="p-fields-content-right"> \
                        <select id="selectTerminalOptions"> \
                            <option value="">' + $.mage.__('Loading') + ' ...</option> \
                        </select> \
                        <label id="errorSelectTerminalOptions" class="error"></label> \
                    </p> \
                </div> \
                <div class="div-fields-content"> \
                    <p class="p-fields-content-right"> \
                        <button type="button" id="terminalTabButton" > \
                            ' + $.mage.__('Next') + ' \
                        </button> \
                    </p> \
                </div> \
            </div>';

        var wizardP2HTML = '<div id="setWebhookSibs"> \
                <p> \
                    <h3>' + $.mage.__('Check the data and change the Webhook if necessary') + '</h3> \
                </p> \
                <div class="div-fields-content"> \
                    <p class="p-fields-content-right"> \
                        <select id="selectClientIDWebhookSecret"> \
                            <option value="">' + $.mage.__('Loading') + ' ...</option> \
                        </select> \
                    </p> \
                </div> \
                <div class="div-fields-content"> \
                    <p class="p-fields-content-right"> \
                        <label for="unconfirmedEmail">' + $.mage.__('Email') + ':</label> \
                        <input type="text" placeholder="' + $.mage.__('Type your email') + '" id="unconfirmedEmail" style="width: 100%" class="sibsBlockedField" /> \
                        <label id="errorUnconfirmedEmail" class="error"></label> \
                    </p> \
                    <p class="p-fields-content-left"> \
                        <label for="unconfirmedIdTerminal">' + $.mage.__('Terminal ID') + ':</label> \
                        <input type="text" placeholder="' + $.mage.__('Enter the Terminal ID') + '" id="unconfirmedIdTerminal" style="width: 100%" class="sibsBlockedField" /> \
                        <label id="errorUnconfirmedIdTerminal" class="error"></label> \
                    </p> \
                </div> \
                <div class="div-fields-content"> \
                    <p class="p-fields-content-right"> \
                        <label for="unconfirmedBearerToken">' + $.mage.__('Bearer Token') + ':</label> \
                        <input type="text" placeholder="' + $.mage.__('Enter the Bearer Token') + '" id="unconfirmedBearerToken" style="width: 100%" class="sibsBlockedField" /> \
                        <label id="errorUnconfirmedBearerToken" class="error"></label> \
                    </p> \
                    <p class="p-fields-content-left"> \
                        <label for="unconfirmedClientId">' + $.mage.__('Client ID') + ':</label> \
                        <input type="text" placeholder="' + $.mage.__('Enter the Client ID') + '" id="unconfirmedClientId" style="width: 100%" class="sibsBlockedField" /> \
                        <label id="errorUnconfirmedClientId" class="error"></label> \
                    </p> \
                </div> \
                <div class="div-fields-content"> \
                    <p class="p-fields-content-right"> \
                        <label for="unconfirmedWebhookSecret">' + $.mage.__('Webhook Secret') + ':</label> \
                        <input type="text" placeholder="' + $.mage.__('Enter the Webhook Secret') + '" id="unconfirmedWebhookSecret" style="width: 100%" class="sibsBlockedField" /> \
                        <label id="errorUnconfirmedWebhookSecret" class="error"></label> \
                    </p> \
                </div> \
                <div class="div-fields-content"> \
                    <p class="p-fields-content-right"> \
                        <button type="button" class="previousWizard whiteButton"> \
                            ' + $.mage.__('Go Back') + ' \
                        </button> \
                        <button type="button" id="unconfirmedData"> \
                            ' + $.mage.__('Finish') + ' \
                        </button> \
                    </p> \
                </div> \
            </div>';

        var sibsConfigAutomatic = jQuery('[id^="row_payment_"][id$="_sibs_sibs_config_automatic"]');
        sibsConfigAutomatic.children().hide();
        sibsConfigAutomatic.append(automaticSBOHTML);
        sibsConfigAutomatic.addClass("sibsConfigAutomatic");
        jQuery('#wizard-radio-config').html(wizardRadioConfiguration);

        var sibsRadioConf = jQuery("input[name=sibsConfigurationRadio]");
        var stepsWizard = null;
        var defaultEnvironment = null;

        sibsRadioConf.change(function(e){
            var valueCheckedSibsRadio = sibsRadioConf.filter(":checked").val();

            if (typeof valueCheckedSibsRadio === "undefined") {
                return false;
            }

            if (valueCheckedSibsRadio == "Automatic") {
                jQuery('#save').attr("disabled", true);
                jQuery('[id^="row_payment_"][id$="_sibs_sibs_config"]').hide();
                ({defaultEnvironment, stepsWizard} = constructWizardConfig());
                jQuery('#wizard-config').show();
            } else {
                jQuery('#wizard-config').hide();
                jQuery('#wizard-config').html('');
                jQuery('[id^="row_payment_"][id$="_sibs_sibs_config"]').show();
                jQuery('#save').removeAttr("disabled");
            }
        });

        sibsRadioConf.trigger("change");

        function constructWizardConfig() {
            jQuery('#wizard-config').html(wizardConfig);

            //create steps function
            let stepsWizard = jQuery("#wizard").steps({
                headerTag: "h3",
                bodyTag: "section",
                enablePagination: false,
                transitionEffect: "slideLeft",
                autoFocus: true,
            });

            jQuery('#wizard-p-0').html(wizardP0HTML);
            jQuery('#wizard-p-1').html(wizardP1HTML);
            jQuery('#wizard-p-2').html(wizardP2HTML);

            jQuery('#wizard-p-1').hide();
            jQuery('#wizard-p-2').hide();
            jQuery("#show_debug_info").hide();

            let defaultEnvironment = jQuery('[id^="payment_"][id$="_sibs_sibs_config_environment"]').find(':selected').val();
            jQuery('#fenvironment').val(defaultEnvironment);

            // open wizard
            jQuery('#openWizard').click(function(event) {
                jQuery('.switch').hide();
                jQuery('#sibsConfigurationModal').show();
            });

            // click wizard
            jQuery('.closeModal').click(function(event) {
                jQuery('.switch').show();
                jQuery('#sibsConfigurationModal').hide();

                restartSteps();
            });

            jQuery('#firstLoginSibs').click(function(event) {
                var ok = true;

                // Verify Login Email
                if (jQuery('#loginSibs').val() == '' || !isEmail(jQuery('#loginSibs').val())) {
                    ok = false;

                    addErrorClass('#loginSibs');

                    var errorMessage = (jQuery('#loginSibs').val() == '') ?
                        $.mage.__('Email is required') :
                        $.mage.__('Incorrect email format');

                    jQuery('#errorLoginSibs').html(errorMessage);
                    jQuery('#errorLoginSibs').show();
                } else {
                    removeErrorClass('#loginSibs');
                    jQuery('#errorLoginSibs').hide();
                }

                // Verify Login Password
                if (jQuery('#passwordSibs').val() == '') {
                    ok = false;

                    addErrorClass('#passwordSibs');

                    jQuery('#errorPassSibs').html($.mage.__('Password is required'));
                    jQuery('#errorPassSibs').show();
                } else {
                    removeErrorClass('#passwordSibs');
                    jQuery('#errorPassSibs').hide();
                }

                if (ok) {
                    showLoading();

                    var defaultEnvironment = jQuery('#fenvironment').val();

                    $.ajax({
                        type: 'POST',
                        url: url.build('/rest/V1/api/sbo/login'),
                        headers: {
                            'Accept':'application/json'
                        },
                        contentType: 'application/json; charset=utf-8',
                        cache: false,
                        async: true,
                        crossDomain: true,
                        dataType: 'json',
                        data: JSON.stringify({
                            'deviceID': userID,
                            'serverMode': defaultEnvironment,
                            'login': jQuery('#loginSibs').val(),
                            'pass': jQuery('#passwordSibs').val()
                        }),
                        beforeSend: (jqXHR) => {
                            /* Override magento's default handler */
                        },
                        success: function(jsonData) {
                            sibsBearerTokenAuthenticationSBO = jsonData.data.token;

                            if (jsonData.data.NxtFlow == 'OK') {
                                wizardTerminals();
                            } else {
                                jQuery('#divLoginSibs').hide();
                                jQuery('#activateLoginSibs').show();
                            }

                            hideLoading();
                        },
                        error: function(errMsg) {
                            sibsBearerTokenAuthenticationSBO = null;

                            addErrorClass('#loginSibs');
                            addErrorClass('#passwordSibs');

                            jQuery('#errorPassSibs').html($.mage.__('Unable to log in with the data provided'));
                            jQuery('#errorPassSibs').show();

                            hideLoading();
                        }
                    });
                }
            });

            jQuery('#secondLoginSibs').click(function(event) {
                var ok = true;

                var activationCodeSibs = jQuery('#activationCode');
                var errorActivationCode = jQuery('#errorActivationCode');

                if (activationCodeSibs.val() == '') {
                    ok = false;

                    addErrorClass('#activationCode');

                    errorActivationCode.html(errorMessage);
                    errorActivationCode.show();
                } else {
                    removeErrorClass('#passwordSibs');
                    errorActivationCode.hide();
                }

                if (ok) {
                    showLoading();
                    $.ajax({
                        type: 'POST',
                        url: url.build('/rest/V1/api/sbo/sms/activate'),
                        headers: {
                            'Accept':'application/json',
                            'Authorization': sibsBearerTokenAuthenticationSBO
                        },
                        contentType: 'application/json; charset=utf-8',
                        cache: false,
                        async: true,
                        crossDomain: true,
                        dataType: 'json',
                        data: JSON.stringify({
                            'deviceID': userID,
                            'serverMode': defaultEnvironment,
                            'code': activationCodeSibs.val()
                        }),
                        beforeSend: (jqXHR) => {
                            /* Override magento's default handler */
                        },
                        success: function(jsonData) {
                            wizardTerminals();
                            errorActivationCode.hide();

                            hideLoading();
                        },
                        error: function(errMsg) {
                            addErrorClass('#activationCode');

                            errorActivationCode.html($.mage.__('Unable to activate login with the code provided'));
                            errorActivationCode.show();

                            hideLoading();
                        }
                    });
                }
            });

            jQuery('#requestNewcode').click(function(event){
                showLoading();

                $.ajax({
                    type: 'POST',
                    url: url.build('/rest/V1/api/sbo/sms/resend'),
                    headers: {
                        'Accept':'application/json',
                        'Authorization': sibsBearerTokenAuthenticationSBO
                    },
                    contentType: 'application/json; charset=utf-8',
                    cache: false,
                    async: true,
                    crossDomain: true,
                    dataType: 'json',
                    data: JSON.stringify({
                        'deviceID': userID,
                        'serverMode': defaultEnvironment
                    }),
                    beforeSend: (jqXHR) => {
                        /* Override magento's default handler */
                    },
                    success: function(jsonData){
                        hideLoading();

                        alert($.mage.__('New code will be sent via SMS'));
                    },
                    error: function(errMsg) {
                        hideLoading();

                        alert($.mage.__('Error when requesting new code via SMS'));
                    }
                });
            });

            jQuery('#selectClientIDWebhookSecret').change(function(event) {
                var selectClientIDWebhookSecret = jQuery(this).val();

                var unconfirmedClientId = jQuery('#unconfirmedClientId');
                var unconfirmedWebhookSecret = jQuery('#unconfirmedWebhookSecret');
                var unconfirmedBearerToken = jQuery('#unconfirmedBearerToken');

                if (selectClientIDWebhookSecret != '') {
                    var explode = selectClientIDWebhookSecret.split('(DivSepSIBS)');

                    if (explode[0] == '') {
                        unconfirmedClientId.removeClass('sibsBlockedField');
                    } else if (!unconfirmedClientId.hasClass('sibsBlockedField')) {
                        unconfirmedClientId.addClass('sibsBlockedField');
                    }

                    if (explode[1] == '') {
                        unconfirmedWebhookSecret.removeClass('sibsBlockedField');
                    } else if (!unconfirmedWebhookSecret.hasClass('sibsBlockedField')) {
                        unconfirmedWebhookSecret.addClass('sibsBlockedField');
                    }

                    if (explode[2] == '') {
                        unconfirmedBearerToken.removeClass('sibsBlockedField');
                    } else if (!unconfirmedBearerToken.hasClass('sibsBlockedField')) {
                        unconfirmedBearerToken.addClass('sibsBlockedField');
                    }

                    unconfirmedClientId.val(explode[0]);
                    unconfirmedWebhookSecret.val(explode[1]);
                    unconfirmedBearerToken.val(explode[2]);
                } else {
                    unconfirmedClientId.removeClass('sibsBlockedField');
                    unconfirmedWebhookSecret.removeClass('sibsBlockedField');
                    unconfirmedBearerToken.removeClass('sibsBlockedField');

                    unconfirmedClientId.val('');
                    unconfirmedWebhookSecret.val('');
                    unconfirmedBearerToken.val('');
                }

                removeErrorClass('#unconfirmedEmail');
                jQuery('#errorUnconfirmedEmail').hide();

                removeErrorClass('#unconfirmedIdTerminal');
                jQuery('#errorUnconfirmedIdTerminal').hide();

                removeErrorClass('#unconfirmedBearerToken');
                jQuery('#errorUnconfirmedBearerToken').hide();

                removeErrorClass('#unconfirmedClientId');
                jQuery('#errorUnconfirmedClientId').hide();

                removeErrorClass('#unconfirmedWebhookSecret');
                jQuery('#errorUnconfirmedWebhookSecret').hide();
            });

            jQuery('#unconfirmedData').click(function(event) {
                showLoading();

                var ok = true;

                // var unconfirmedWebhookSecret = jQuery('#unconfirmedWebhookSecret').val();

                // Verify Email
                if (jQuery('#unconfirmedEmail').val() == '' || !isEmail(jQuery('#unconfirmedEmail').val())) {
                    ok = false;

                    addErrorClass('#unconfirmedEmail');

                    var errorMessage = (jQuery('#unconfirmedEmail').val() == '') ?
                        $.mage.__('Email is required') :
                        $.mage.__('Incorrect email format');

                    jQuery('#errorUnconfirmedEmail').html(errorMessage);
                    jQuery('#errorUnconfirmedEmail').show();
                } else {
                    removeErrorClass('#unconfirmedEmail');
                    jQuery('#errorUnconfirmedEmail').hide();
                }

                // Verify Terminal ID
                if (jQuery('#unconfirmedIdTerminal').val() == '') {
                    ok = false;

                    addErrorClass('#unconfirmedIdTerminal');

                    jQuery('#errorUnconfirmedIdTerminal').html($.mage.__('Terminal ID is required'));
                    jQuery('#errorUnconfirmedIdTerminal').show();
                } else {
                    removeErrorClass('#unconfirmedIdTerminal');
                    jQuery('#errorUnconfirmedIdTerminal').hide();
                }

                // Verify Bearer Token
                if (jQuery('#unconfirmedBearerToken').val() == '') {
                    ok = false;

                    addErrorClass('#unconfirmedBearerToken');

                    jQuery('#errorUnconfirmedBearerToken').html($.mage.__('Bearer Token is required'));
                    jQuery('#errorUnconfirmedBearerToken').show();
                } else {
                    removeErrorClass('#unconfirmedBearerToken');
                    jQuery('#errorUnconfirmedBearerToken').hide();
                }

                // Verify Client ID
                if (jQuery('#unconfirmedClientId').val() == '') {
                    ok = false;

                    addErrorClass('#unconfirmedClientId');

                    jQuery('#errorUnconfirmedClientId').html($.mage.__('Customer ID is required'));
                    jQuery('#errorUnconfirmedClientId').show();
                } else {
                    removeErrorClass('#unconfirmedClientId');
                    jQuery('#errorUnconfirmedClientId').hide();
                }

                // Verify Webhook Secret
                if (jQuery('#unconfirmedWebhookSecret').val() == '') {
                    ok = false;

                    addErrorClass('#unconfirmedWebhookSecret');

                    jQuery('#errorUnconfirmedWebhookSecret').html($.mage.__('Webhook Secret is required'));
                    jQuery('#errorUnconfirmedWebhookSecret').show();
                } else {
                    removeErrorClass('#unconfirmedWebhookSecret');
                    jQuery('#errorUnconfirmedWebhookSecret').hide();
                }

                if (!ok) {
                    hideLoading();

                    return ok;
                }

                jQuery('[id^="payment_"][id$="_sibs_sibs_config_terminal_code"]').val(jQuery('#unconfirmedIdTerminal').val());
                jQuery('[id^="payment_"][id$="_sibs_sibs_config_bearer_token"]').val(jQuery('#unconfirmedBearerToken').val());
                jQuery('[id^="payment_"][id$="_sibs_sibs_config_client_id"]').val(jQuery('#unconfirmedClientId').val());
                jQuery('[id^="payment_"][id$="_sibs_sibs_config_webhook_secret"]').val(jQuery('#unconfirmedWebhookSecret').val());
                jQuery('[id^="payment_"][id$="_sibs_sibs_config_environment"]').val(jQuery('#defaultEnvironment').val());

                jQuery('#config-edit-form')[0].submit();

                hideLoading();

                return ok;
            });

            jQuery('#wizardTerminals').click(function(event) {
                wizardTerminals();
            });

            jQuery('#terminalTabButton').click(function(event) {
                var ok = true;

                // Verify Client ID
                if (jQuery('#selectTerminalOptions').val() == '') {
                    ok = false;

                    addErrorClass('#selectTerminalOptions');

                    jQuery('#errorSelectTerminalOptions').html($.mage.__('Terminal is required'));
                    jQuery('#errorSelectTerminalOptions').show();
                } else {
                    removeErrorClass('#selectTerminalOptions');
                    jQuery('#errorSelectTerminalOptions').hide();
                }

                if (ok) {
                    wizardFieldsUnconfirmed(jQuery('#selectTerminalOptions').val());
                }
            });

            jQuery('#show_log').click(function() {
                jQuery('#show_debug_info').toggle();
            });

            jQuery('#webhookurl').click(function(event) {
                event.preventDefault();
            });

            jQuery('.previousWizard').click(function(event){
                stepsWizard.steps('previous');
            });

            jQuery('.done').click(function(event){
                event.stopPropagation();

                return false;
            });

            return {defaultEnvironment, stepsWizard};
        }

        function wizardTerminals() {
            stepsWizard.steps('next');

            showLoading();

            $.ajax({
                type: 'POST',
                url: url.build('/rest/V1/api/sbo/terminal/list'),
                headers: {
                    'Accept':'application/json',
                    'Authorization': sibsBearerTokenAuthenticationSBO
                },
                contentType: 'application/json; charset=utf-8',
                cache: false,
                async: true,
                crossDomain: true,
                dataType: 'json',
                data: JSON.stringify({
                    'deviceID': userID,
                    'serverMode': defaultEnvironment
                }),
                beforeSend: (jqXHR) => {
                    /* Override magento's default handler */
                },
                success: function(jsonData) {
                    var defaultOption = $.mage.__('Select the Terminal');

                    jQuery('#selectTerminalOptions').html('');
                    jQuery('#selectTerminalOptions').append('<option value="">' + defaultOption + '</option>');

                    jQuery.each(jsonData.data.terminalList, function(i, val) {
                        jQuery('#selectTerminalOptions').append(
                            '<option value="' + val.optionData + '">' + val.description + '</option>'
                        );
                    });

                    hideLoading();
                },
                error: function(errMsg) {
                    alert($.mage.__('No terminals were found'));

                    hideLoading();
                }
            });
        }

        function wizardFieldsUnconfirmed(mrchInfo) {
			var explode = mrchInfo.split('-');

			jQuery('#unconfirmedEmail').val(jQuery('#loginSibs').val());
			jQuery('#unconfirmedBearerToken').val('');
			jQuery('#unconfirmedIdTerminal').val(explode[0]);

            showLoading();

			$.ajax({
				type: 'POST',
				url: url.build('/rest/V1/api/sbo/webhook/list'),
                headers: {
                    'Accept':'application/json',
                    'Authorization': sibsBearerTokenAuthenticationSBO
                },
                contentType: 'application/json; charset=utf-8',
				cache: false,
				async: true,
				crossDomain: true,
				dataType: 'json',
				data: JSON.stringify({
					'deviceID': userID,
					'serverMode': defaultEnvironment,
                    'login': jQuery('#loginSibs').val(),
					'pass': jQuery('#passwordSibs').val(),
					'TermnlCd': explode[0],
					'AccptrCd': explode[1],
					'MrchntCd': explode[2]
				}),
                beforeSend: (jqXHR) => {
                    /* Override magento's default handler */
                },
				success: function(jsonData) {
                    var defaultOption = $.mage.__('Select the Webhook');

					jQuery('#selectClientIDWebhookSecret').html('');
                    jQuery('#selectClientIDWebhookSecret').append('<option value="">' + defaultOption + '</option>');

					jQuery.each(jsonData.data.webhookList, function(i, val) {
						jQuery('#selectClientIDWebhookSecret').append(
                            '<option value="' + val.clientID + '(DivSepSIBS)' + val.webhookSecret
                            + '(DivSepSIBS)' + val.bearerToken + '">' + val.description + '</option>'
                        );
					});

					jQuery('#selectClientIDWebhookSecret').trigger('change');

                    stepsWizard.steps('next');

					hideLoading();
				},
				error: function(errMsg) {
					alert($.mage.__('No ClientID or Webhook Secret found'));

                    hideLoading();
				}
			});
		}

        // restart steps just when trying to login
        function restartSteps() {
            sibsBearerTokenAuthenticationSBO = null;

            var tab1 = jQuery('#wizard-t-1');
            var tab2 = jQuery('#wizard-t-2');
            var tab3 = jQuery('#wizard-t-3');

            var currentIndex = stepsWizard.steps('getCurrentIndex');

            for(var i = 0; i < currentIndex; i++){
                stepsWizard.steps('previous');
            }

            jQuery('#divLoginSibs').show();
            jQuery('#activateLoginSibs').hide();

            tab1.parent().removeClass('done');
            tab1.parent().addClass('disabled');

            tab2.parent().removeClass('done');
            tab2.parent().addClass('disabled');

            tab3.parent().removeClass('done');
            tab3.parent().addClass('disabled');
        }

        function showLoading() {
			jQuery('.lds-ring').css('visibility', 'visible');
		}

		function hideLoading() {
			jQuery('.lds-ring').css('visibility', 'hidden');
		}

        function uuid() {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				var r = Math.random() * 16 | 0,
					v = c == 'x' ? r : (r & 0x3 | 0x8);
				return v.toString(16);
			});
		}

        function isEmail(email) {
			var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			return regex.test(email);
		}

        // show errors
        function addErrorClass(place) {
			jQuery(place).addClass('error');
			jQuery(place).prev().addClass('error');
		}

		// hide errors
		function removeErrorClass(place) {
			jQuery(place).removeClass('error');
			jQuery(place).prev().removeClass('error');
		}

        // get base URL
		function getBaseUrl() {
			let origin = window.location.origin;
            let all_pathnames = window.location.pathname.split('/');
            let admin_index = all_pathnames.lastIndexOf('admin');
            let pathnames = all_pathnames.splice(0, admin_index-1);

            return origin + pathnames.join('/');
		}
    });
});
