// JS assets for plugin bambu_printer
(function () {
    try {
        // source: plugin/bambu_printer/js/bambu_printer.js
        /*
         * View model for OctoPrint-BambuPrinter
         *
         * Author: jneilliii
         * License: AGPLv3
         */
        
        $(function () {
            function Bambu_printerViewModel(parameters) {
                var self = this;
        
                self.settingsViewModel = parameters[0];
                self.filesViewModel = parameters[1];
        
                self.getAuthToken = function (data) {
                    self.settingsViewModel.settings.plugins.bambu_printer.auth_token("");
                    OctoPrint.simpleApiCommand("bambu_printer", "register", {
                        "email": self.settingsViewModel.settings.plugins.bambu_printer.email(),
                        "password": $("#bambu_cloud_password").val(),
                        "region": self.settingsViewModel.settings.plugins.bambu_printer.region(),
                        "auth_token": self.settingsViewModel.settings.plugins.bambu_printer.auth_token()
                    })
                        .done(function (response) {
                            console.log(response);
                            self.settingsViewModel.settings.plugins.bambu_printer.auth_token(response.auth_token);
                            self.settingsViewModel.settings.plugins.bambu_printer.username(response.username);
                        });
                };
        
                /*$('#files div.upload-buttons > span.fileinput-button:first, #files div.folder-button').remove();
                $('#files div.upload-buttons > span.fileinput-button:first').removeClass('span6').addClass('input-block-level');
        
                self.onBeforePrintStart = function(start_print_command) {
                    let confirmation_html = '' +
                        '            <div class="row-fluid form-vertical">\n' +
                        '                <div class="control-group">\n' +
                        '                    <label class="control-label">' + gettext("Plate Number") + '</label>\n' +
                        '                    <div class="controls">\n' +
                        '                        <input type="number" min="1" value="1" id="bambu_printer_plate_number" class="input-mini">\n' +
                        '                    </div>\n' +
                        '                </div>\n' +
                        '            </div>';
        
                    if(!self.settingsViewModel.settings.plugins.bambu_printer.always_use_default_options()){
                        confirmation_html += '\n' +
                            '            <div class="row-fluid">\n' +
                            '                <div class="span6">\n' +
                            '                    <label class="checkbox"><input id="bambu_printer_timelapse" type="checkbox"' + ((self.settingsViewModel.settings.plugins.bambu_printer.timelapse()) ? ' checked' : '') + '> ' + gettext("Enable timelapse") + '</label>\n' +
                            '                    <label class="checkbox"><input id="bambu_printer_bed_leveling" type="checkbox"' + ((self.settingsViewModel.settings.plugins.bambu_printer.bed_leveling()) ? ' checked' : '') + '> ' + gettext("Enable bed leveling") + '</label>\n' +
                            '                    <label class="checkbox"><input id="bambu_printer_flow_cali" type="checkbox"' + ((self.settingsViewModel.settings.plugins.bambu_printer.flow_cali()) ? ' checked' : '') + '> ' + gettext("Enable flow calibration") + '</label>\n' +
                            '                </div>\n' +
                            '                <div class="span6">\n' +
                            '                    <label class="checkbox"><input id="bambu_printer_vibration_cali" type="checkbox"' + ((self.settingsViewModel.settings.plugins.bambu_printer.vibration_cali()) ? ' checked' : '') + '> ' + gettext("Enable vibration calibration") + '</label>\n' +
                            '                    <label class="checkbox"><input id="bambu_printer_layer_inspect" type="checkbox"' + ((self.settingsViewModel.settings.plugins.bambu_printer.layer_inspect()) ? ' checked' : '') + '> ' + gettext("Enable first layer inspection") + '</label>\n' +
                            '                    <label class="checkbox"><input id="bambu_printer_use_ams" type="checkbox"' + ((self.settingsViewModel.settings.plugins.bambu_printer.use_ams()) ? ' checked' : '') + '> ' + gettext("Use AMS") + '</label>\n' +
                            '                </div>\n' +
                            '            </div>\n';
                    }
        
                    showConfirmationDialog({
                        title: "Bambu Print Options",
                        html: confirmation_html,
                        cancel: gettext("Cancel"),
                        proceed: [gettext("Print"), gettext("Always")],
                        onproceed: function (idx) {
                            if(idx === 1){
                                self.settingsViewModel.settings.plugins.bambu_printer.timelapse($('#bambu_printer_timelapse').is(':checked'));
                                self.settingsViewModel.settings.plugins.bambu_printer.bed_leveling($('#bambu_printer_bed_leveling').is(':checked'));
                                self.settingsViewModel.settings.plugins.bambu_printer.flow_cali($('#bambu_printer_flow_cali').is(':checked'));
                                self.settingsViewModel.settings.plugins.bambu_printer.vibration_cali($('#bambu_printer_vibration_cali').is(':checked'));
                                self.settingsViewModel.settings.plugins.bambu_printer.layer_inspect($('#bambu_printer_layer_inspect').is(':checked'));
                                self.settingsViewModel.settings.plugins.bambu_printer.use_ams($('#bambu_printer_use_ams').is(':checked'));
                                self.settingsViewModel.settings.plugins.bambu_printer.always_use_default_options(true);
                                self.settingsViewModel.saveData();
                            }
                            // replace this with our own print command API call?
                            start_print_command();
                        },
                        nofade: true
                    });
                    return false;
                };*/
            }
        
            OCTOPRINT_VIEWMODELS.push({
                construct: Bambu_printerViewModel,
                // ViewModels your plugin depends on, e.g. loginStateViewModel, settingsViewModel, ...
                dependencies: ["settingsViewModel", "filesViewModel"],
                // Elements to bind to, e.g. #settings_plugin_bambu_printer, #tab_plugin_bambu_printer, ...
                elements: ["#bambu_printer_print_options", "#settings_plugin_bambu_printer"]
            });
        });
        
        ;
        
    } catch (error) {
        log.error("Error in JS assets for plugin bambu_printer:", `${exc.message}
${exc.stack || exc}`);
    }
})();

// JS assets for plugin obico
(function () {
    try {
        // source: plugin/obico/js/ObicoSettings.js
        /*
         * View model for Obico Settings
         *
         * Author:  The Obico team
         * License: AGPLv3
         */
        $(function () {
        
            $(function() {
                $('.obico-collapsable__title').click(function() {
                    $(this).parent().toggleClass('opened');
                })
            });
        
            function ObicoSettingsViewModel(parameters) {
                var self = this;
        
                const defaultServerAddress = 'https://app.obico.io';
                function getServerType(serverAddress) {
                    return serverAddress == defaultServerAddress ? 'cloud' : 'self-hosted';
                }
        
                // assign the injected parameters, e.g.:
                // self.loginStateViewModel = parameters[0];
                self.obicoWizardViewModel = parameters[0];
                self.settingsViewModel = parameters[1];
                self.wizardViewModel = parameters[2];
        
                self.alertsShown = {};
                self.piCamResolutionOptions = [{ id: "low", text: "Low" }, { id: "medium", text: "Medium" }, { id: "high", text: "High" }, { id: "ultra_high", text: "Ultra High" }];
                self.isWizardShown = ko.observable(
                    retrieveFromLocalStorage('disableTSDWizardAutoPopupUntil', 0) > new Date().getTime()
                );
                self.showDetailPage = ko.observable(false);
                self.serverStatus = ko.mapping.fromJS({ is_connected: false, status_posted_to_server_ts: 0, bailed_because_tsd_plugin_running: false });
                self.streaming = ko.mapping.fromJS({ is_pi_camera: false, webrtc_streaming: false, compat_streaming: false});
                self.linkedPrinter = ko.mapping.fromJS({ is_pro: false, id: null, name: null});
                self.errorStats = ko.mapping.fromJS({ server: { attempts: 0, error_count: 0, first: null, last: null }, webcam: { attempts: 0, error_count: 0, first: null, last: null }});
                self.serverTestStatusCode = ko.observable(null);
                self.serverTested = ko.observable('never');
                self.sentryOptedIn = ko.pureComputed(function () {
                    return self.settingsViewModel.settings.plugins.obico.sentry_opt() === "in";
                }, self);
                self.configured = ko.pureComputed(function () {
                    return self.settingsViewModel.settings.plugins.obico.auth_token
                        && self.settingsViewModel.settings.plugins.obico.auth_token();
                }, self);
                self.wizardAutoPoppedup = ko.observable(false);
                self.disableWizardAutoPopUp = ko.observable(false);
                self.serverType = ko.observable('cloud');
                self.hasTsdMigratedModalShown = ko.observable(false);
        
                self.onStartupComplete = function (plugin, data) {
                    self.fetchPluginStatus();
                    self.serverType(getServerType(self.settingsViewModel.settings.plugins.obico.endpoint_prefix()));
                };
        
                self.onSettingsBeforeSave = function() {
                    self.serverType(getServerType(self.settingsViewModel.settings.plugins.obico.endpoint_prefix()));
                }
        
                self.hasServerErrors = function() {
                    return self.errorStats.server.error_count() > 0;
                };
        
                self.hasWebcamErrors = function() {
                    return self.errorStats.webcam.error_count() > 0;
                };
        
                self.serverErrorRate = function() {
                    return Math.round(self.errorStats.server.error_count() / self.errorStats.server.attempts() * 100);
                };
        
                self.webcamErrorRate = function() {
                    return Math.round(self.errorStats.webcam.error_count() / self.errorStats.webcam.attempts() * 100);
                };
        
                self.serverTestSucceeded = function() {
                    return self.serverTestStatusCode() == 200;
                };
        
                self.serverTestUnknownError = function() {
                    return self.serverTestStatusCode() != null && self.serverTestStatusCode() != 401 && self.serverTestStatusCode() != 200;
                };
        
                self.fetchPluginStatus = function() {
                    apiCommand({
                        command: "get_plugin_status",
                    })
                    .done(function (data) {
                        ko.mapping.fromJS(data.server_status, self.serverStatus);
                        ko.mapping.fromJS(data.streaming_status, self.streaming);
                        ko.mapping.fromJS(data.error_stats, self.errorStats);
                        ko.mapping.fromJS(data.linked_printer, self.linkedPrinter);
        
                        _.get(data, 'alerts', []).forEach(function (alertMsg) {
                            self.displayAlert(alertMsg);
                        })
        
                        if (self.settingsViewModel.settings.plugins.obico.tsd_migrated
                            && self.settingsViewModel.settings.plugins.obico.tsd_migrated() == 'yes'
                            && !self.hasTsdMigratedModalShown()) {
                            self.showTsdMigratedModal();
                            self.hasTsdMigratedModalShown(true);
                            return;
                        }
        
                        if (!self.configured() && !self.isWizardShown() && !self.wizardViewModel.isDialogActive()) {
                            self.showWizardModal();
                            self.isWizardShown(true);
                            return;
                        }
        
                        if (_.get(data, 'sentry_opt') === "out") {
                            var sentrynotice = new PNotify({
                                title: "Obico",
                                text: "<p>Turn on bug reporting to help us make Obico plugin better?</p><p>The debugging info included in the report will be anonymized.</p>",
                                hide: false,
                                destroy: true,
                                confirm: {
                                    confirm: true,
                                },
                            });
                            sentrynotice.get().on('pnotify.confirm', function () {
                                self.toggleSentryOpt();
                            });
                        }
                    });
                };
        
                self.testServerConnection = function() {
                    self.serverTested('testing');
                    apiCommand({
                        command: "test_server_connection",
                    })
                    .done(function (data) {
                        self.serverTested('tested');
                        self.serverTestStatusCode(data.status_code);
                    });
                };
        
                self.toggleSentryOpt = function (ev) {
                    apiCommand({
                        command: "toggle_sentry_opt",
                    });
                    return true;
                };
        
                self.resetEndpointPrefix = function () {
                    self.settingsViewModel.settings.plugins.obico.endpoint_prefix(defaultServerAddress);
                    return true;
                };
        
                self.clearEndpointPrefix = function () {
                    self.settingsViewModel.settings.plugins.obico.endpoint_prefix('');
                    return true;
                };
        
                self.selectPage = function(page) {
                    self.showDetailPage(true);
        
                    switch (page) {
                        case 'troubleshooting':
                            $('li[data-page="advanced"]').removeClass('active');
                            $('#obico-advanced').removeClass('active');
                            $('li[data-page="troubleshooting"]').addClass('active');
                            $('#obico-troubleshooting').addClass('active');
                            break;
                        case 'advanced':
                            $('li[data-page="troubleshooting"]').removeClass('active');
                            $('#obico-troubleshooting').removeClass('active');
                            $('li[data-page="advanced"]').addClass('active');
                            $('#obico-advanced').addClass('active');
                            break;
                    }
                };
        
                self.returnToSelection = function() {
                    self.showDetailPage(false);
                }
        
                /*** Plugin error alerts */
        
                self.onDataUpdaterPluginMessage = function (plugin, data) {
                    if (plugin != "obico") {
                        return;
                    }
        
                    if (data.plugin_updated) {
                        self.fetchPluginStatus();
                    }
        
                    if (data.printer_autolinked) {
                        self.fetchPluginStatus();
                        self.obicoWizardViewModel.toStep(5);
                        self.obicoWizardViewModel.startAutoCloseTimout();
                    }
                }
        
                self.displayAlert = function (alertMsg) {
        
                    var AVAILABLE_BUTTONS = {
                        more_info: {
                            text: "More Info",
                            click: function (notice) {
                                window.open(alertMsg.info_url, '_blank');
                                notice.remove();
                            },
                        },
                        never: {
                            text: "Never Show Again",
                            click: function (notice) {
                                saveToLocalStorage(ignoredItemPath, true);
                                notice.remove();
                            },
                            addClass: "never_button"
                        },
                        ok: {
                            text: "OK",
                            click: function (notice) {
                                notice.remove();
                            },
                            addClass: "ok_button"
                        },
                        close: {
                            text: "Close",
                            addClass: "remove_button"
                        },
                        diagnose: {
                            text: "Details",
                            click: function (notice) {
                                self.showDiagnosticReportModal();
                                notice.remove();
                            }
                        },
                    };
        
        
                    var ignoredItemPath = "ignored." + alertMsg.cause + "." + alertMsg.level;
                    if (retrieveFromLocalStorage(ignoredItemPath, false)) {
                        return;
                    }
        
                    var showItemPath = alertMsg.cause + "." + alertMsg.level;
                    if (_.get(self.alertsShown, showItemPath, false)) {
                        return;
                    }
                    _.set(self.alertsShown, showItemPath, true);
        
                    var msgType = "error";
                    if (alertMsg.level === "warning") {
                        msgType = "notice";
                    }
        
                    var buttons = _.map(alertMsg.buttons, function(k) {
                        return AVAILABLE_BUTTONS[k];
                    });
        
                    hiddenButtons = [];
        
                    // PNotify needs this dance to hide the default "Ok" and "Cancel" button
                    ['ok', 'close'].forEach(function(k) {
                        if (!_.includes(alertMsg.buttons, k)) {
                            buttons.push(AVAILABLE_BUTTONS[k]);
                            hiddenButtons.push(AVAILABLE_BUTTONS[k].addClass);
                        }
                    })
        
                    if (alertMsg.text) {
                        new PNotify({
                            title: "Obico",
                            text: alertMsg.text,
                            type: msgType,
                            hide: false,
                            confirm: {
                                confirm: true,
                                buttons: buttons,
                            },
                            history: {
                                history: false
                            },
                            before_open: function (notice) {
                                hiddenButtons.forEach(function(className) {
                                    notice
                                        .get()
                                        .find("." + className)
                                        .remove();
                                });
                            }
                        });
                    }
                };
        
                self.showDiagnosticReportModal = function () {
                    $('#diagnosticReportModal').modal();
                };
        
                self.showWizardModal = function (maybeViewModel) {
                    self.wizardAutoPoppedup(!Boolean(maybeViewModel)); // When it's triggered by user click, maybeViewModel is not undefined
                    $('#wizardModal').modal({backdrop: 'static', keyboard: false});
                };
        
                $('#wizardModal').on('shown', function(){
                    self.obicoWizardViewModel.reset();
                });
                $('#wizardModal').on('hidden', function(){
                    if (self.disableWizardAutoPopUp()) {
                        saveToLocalStorage('disableTSDWizardAutoPopupUntil', (new Date()).getTime() + 1000*60*60*24*30); // Not show for 30 days
                    }
                });
        
                self.showTsdMigratedModal = function (maybeViewModel) {
                    $('#tsdMigratedModal').modal();
                };
                self.hideTsdMigratedModal = function() {
                    $('#tsdMigratedModal').modal('hide');
                    self.settingsViewModel.saveData({plugins: {obico: {tsd_migrated: 'confirmed'}}});
                }
            }
        
        
            // Helper methods
            function apiCommand(data) {
                return $.ajax("api/plugin/obico", {
                    method: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(data)
                });
            }
        
            var LOCAL_STORAGE_KEY = 'plugin.obico';
        
            function localStorageObject() {
                var retrievedObject = localStorage.getItem(LOCAL_STORAGE_KEY);
                if (!retrievedObject) {
                    retrievedObject = '{}';
                }
                return JSON.parse(retrievedObject);
            }
        
            function retrieveFromLocalStorage(itemPath, defaultValue) {
                return _.get(localStorageObject(), itemPath, defaultValue);
            }
        
            function saveToLocalStorage(itemPath, value) {
                var retrievedObject = localStorageObject();
                _.set(retrievedObject, itemPath, value);
                localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(retrievedObject));
            }
        
        
            /* view model class, parameters for constructor, container to bind to
             * Please see http://docs.octoprint.org/en/master/plugins/viewmodels.html#registering-custom-viewmodels for more details
             * and a full list of the available options.
             */
            OCTOPRINT_VIEWMODELS.push({
                construct: ObicoSettingsViewModel,
                // ViewModels your plugin depends on, e.g. loginStateViewModel, settingsViewModel, ...
                dependencies: ["obicoWizardViewModel", "settingsViewModel", "wizardViewModel"],
                // Elements to bind to, e.g. #settings_plugin_obico, #tab_plugin_obico, ...
                elements: [
                    "#settings_plugin_obico",
                ]
            });
        
        });
        
        ;
        
        // source: plugin/obico/js/ObicoWizard.js
        /*
         * View model for Obico Wizard
         *
         * Author:  The Obico team
         * License: AGPLv3
         */
        $(function () {
        
            function apiCommand(data) {
                return $.ajax("api/plugin/obico", {
                    method: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(data)
                });
            }
        
            function ObicoWizardViewModel(parameters) {
                var self = this;
        
                const defaultServerAddress = 'https://app.obico.io';
                function getServerType(serverAddress) {
                    return serverAddress == defaultServerAddress ? 'cloud' : 'self-hosted';
                }
        
                // assign the injected parameters, e.g.:
                // self.loginStateViewModel = parameters[0];
                self.settingsViewModel = parameters[0];
        
                self.step = ko.observable(1);
                self.mobileFlow = ko.observable(true);
                self.securityCode = ko.observable('');
                self.verifying = ko.observable(false);
                self.userAgreementChecked = ko.observable(true);
                self.printerName = ko.observable('');
                self.printerNameTimeoutId = ko.observable(null);
                self.currentFeatureSlide = ko.observable(1);
        
                self.serverType = ko.observable('cloud');
        
                self.onStartupComplete = function () {
                    self.reset();
                };
        
                self.isServerInvalid = ko.observable(false);
        
                self.checkSeverValidity = (url) => {
                    return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/.test(url);
                }
        
                // Handle verification code typing:
        
                $.find('.obico-verification-code-input input').forEach(function(input) {
                    // Add event listener for paste event
                    $(input).on('paste', handlePaste);
        
                    // Handle typing in verification code to automatically move cursor back/forward
                    $(input).on('keydown', handleKeydown);
                });
        
                // Paste verification code digit by digit
                function handlePaste(event) {
                    let text = (event.originalEvent.clipboardData || window.clipboardData).getData('text');
                    for (let i = 0; i < text.length; i++) {
                        let char = text[i];
                        appendToVerificationCode(char);
                    }
        
                    event.preventDefault();
                }
        
                // Move cursor back/forward
                function handleKeydown(event) {
        
                    // Skip Paste event
                    if (event.key === 'Meta' || event.key === 'Control' || event.originalEvent.code === 'KeyV') {
                        return true;
                    }
        
                    if (event.key === 'Backspace') {
                        for (let i = 6; i >= 1; i--) {
                            let input = $('.obico-verification-code-input input[data-number='+ i +']');
                            if (input.val()) {
                                input.val('').trigger('focus');
                                self.securityCode(self.securityCode().slice(0, -1));
                                clearVerificationCodeMessages();
                                break;
                            }
                        }
                    } else {
                        appendToVerificationCode(event.key);
                    }
        
                    return false;
                }
        
                // Append digit to verification code
                function appendToVerificationCode(char) {
                    let availableInputs = ['0','1','2','3','4','5','6','7','8','9'];
        
                    if (!availableInputs.includes(char)) {
                        return false;
                    }
        
                    for (let i = 1; i <= 6; i++) {
                        let input = $('.obico-verification-code-input input[data-number='+ i +']');
        
                        if (!input.val()) {
                            // Put value to input visible to user
                            input.val(char);
        
                            // Move cursor forward
                            if (i < 6) {
                                $('.obico-verification-code-input input[data-number='+ (i + 1) +']').trigger('focus');
                            }
        
                            // Append char to inner code
                            self.securityCode(self.securityCode() + char);
        
                            // Clear all error and other messages for the input
                            if (self.securityCode().length < 6) {
                                clearVerificationCodeMessages();
                            }
        
                            return true;
                        }
                    }
        
                    return false;
                }
        
                // Clear error messages from verification code
                function clearVerificationCodeMessages() {
                    $('.obico-verification-wrapper').removeClass(['error', 'success', 'unknown']);
                }
        
                self.startAutoCloseTimout = function() {
                    setTimeout(function() {
                        $('.obico-auto-close').addClass('active');
                        setTimeout(function() { self.hideWizardModal(); }, 10000); // auto-close in 10s
                    }, 500) // Add .5s delay to make transition visible
                }
        
        
                self.nextStep = function() {
                    if (self.step() === 1) {
                        let url = self.settingsViewModel.settings.plugins.obico.endpoint_prefix()
        
                        if (self.serverType() === 'self-hosted') {
                            if (self.checkSeverValidity(url)) {
                                self.isServerInvalid(false);
                            } else {
                                self.isServerInvalid(true);
                                return;
                            }
                        }
        
                        self.serverType(getServerType(url))
                        if (self.settingsViewModel.settings.plugins.obico.endpoint_prefix() !== self.initialServerEndpointPrefix) {
                            self.settingsViewModel.saveData({plugins: {obico: {endpoint_prefix: url}}});
                        }
                    }
        
                    self.toStep(self.step() + 1);
        
                    if (self.step() === 4) {
                        $('.obico-modal[aria-hidden="false"] .obico-verification-code-input input[data-number=1]').trigger('focus');
                    } else if (self.step() === 5) {
                        // Close button with countdown animation
                        self.startAutoCloseTimout()
                    }
                };
        
                self.prevStep = function() {
                    self.toStep(self.step() - 1);
                };
        
                self.toStep = function(nextStep) {
                    self.step(nextStep);
                };
        
        
                self.toggleCheck = function() {
                    self.userAgreementChecked(!self.userAgreementChecked());
                }
        
                self.securityCode.subscribe(function(code) {
                    self.verifySecurityCode(code);
                });
        
                self.printerName.subscribe(function() {
                    if (self.printerNameTimeoutId()) {
                        clearTimeout(self.printerNameTimeoutId());
                    }
                    let newTimeoutId = setTimeout(self.savePrinterName, 1000);
                    self.printerNameTimeoutId(newTimeoutId);
                })
        
                self.verifySecurityCode = function(code) {
                    if (code.length !== 6) {
                        return;
                    }
                    self.verifying(true);
        
                    apiCommand({
                        command: "verify_code",
                        code: code,
                        endpoint_prefix: $('#endpoint_prefix-input').val(),
                    })
                        .done(function(apiStatus) {
                            if (apiStatus.succeeded == null) {
                                $('.obico-verification-wrapper').addClass('unknown');
                            }
                            else if (apiStatus.succeeded) {
                                $('.obico-verification-wrapper').addClass('success');
                                self.printerName(apiStatus.printer.name);
                                self.nextStep();
                            } else {
                                $('.obico-verification-wrapper').addClass('error');
                            }
                        })
                        .fail(function() {
                            $('.obico-verification-wrapper').addClass('unknown');
                        })
                        .always(function () {
                            self.verifying(false);
                        });
                };
        
                self.resetEndpointPrefix = function () {
                    self.settingsViewModel.settings.plugins.obico.endpoint_prefix(defaultServerAddress);
                    return true;
                };
        
                self.clearEndpointPrefix = function () {
                    self.settingsViewModel.settings.plugins.obico.endpoint_prefix('');
                    return true;
                };
        
                self.reset = function() {
                    self.step(1);
                    self.verifying(false);
                    self.securityCode('');
                    $('.obico-auto-close').removeClass('active');
        
                    let verificationWrapper = $('.obico-verification-wrapper');
                    verificationWrapper.removeClass('success error unknown');
        
                    for (let i = 1; i <= 6; i++) {
                        verificationWrapper.find('.obico-verification-code-input input[data-number='+ i +']').val('');
                    }
                    self.serverType(getServerType(self.settingsViewModel.settings.plugins.obico.endpoint_prefix()));
                    self.initialServerEndpointPrefix = self.settingsViewModel.settings.plugins.obico.endpoint_prefix();
                }
        
                self.hideWizardModal = function() {
                    $('.obico-auto-close').removeClass('active');
                    $('#wizardModal').modal('hide');
                }
        
                // Next feature in the slider on home screen
                self.nextFeature = function() {
                    let container = $('.obico-features').last();
                    let slidesCount = container.find('.obico-feature').length;
                    let currentSlide = self.currentFeatureSlide();
                    let nextSlide = currentSlide === slidesCount ? 1 : currentSlide + 1;
        
                    container.find('.obico-feature[data-number="'+ currentSlide +'"]').animate({
                        left: '-100%'
                    }, {duration: 500, queue: false});
        
                    container.find('.obico-feature[data-number="'+ nextSlide +'"]').animate({
                        left: '0'
                    },
                    500,
                    function() {
                        let next = nextSlide === slidesCount ? 1 : nextSlide + 1;
                        container.find('.obico-feature[data-number="'+ next +'"]').css('left', '100%');
                    });
        
                    self.currentFeatureSlide(nextSlide);
                }
        
                setInterval(self.nextFeature, 3000);
            }
        
            /* view model class, parameters for constructor, container to bind to
             * Please see http://docs.octoprint.org/en/master/plugins/viewmodels.html#registering-custom-viewmodels for more details
             * and a full list of the available options.
             */
            OCTOPRINT_VIEWMODELS.push({
                construct: ObicoWizardViewModel,
                // ViewModels your plugin depends on, e.g. loginStateViewModel, settingsViewModel, ...
                dependencies: ["settingsViewModel"],
                // Elements to bind to, e.g. #settings_plugin_obico, #tab_plugin_obico, ...
                elements: [
                    "#wizard_plugin_obico",
                    "#obico-wizard",
                ]
            });
        
        });
        
        ;
        
    } catch (error) {
        log.error("Error in JS assets for plugin obico:", `${exc.message}
${exc.stack || exc}`);
    }
})();
