Viewing File: /usr/local/cpanel/whostmgr/docroot/templates/accounts/createacct.js

// Copyright 2022 cPanel, L.L.C. - All rights reserved.
// copyright@cpanel.net
// https://cpanel.net
// This code is subject to the cPanel license. Unauthorized copying is prohibited

/* eslint-disable new-cap, camelcase, strict, no-use-before-define */
/**
 * Page-specific javascript for Create Account page in WHM.
 * @module CreateAccount
 **/

(function() {

    var VALID = {},
        DOM = YAHOO.util.Dom,
        EVENT = YAHOO.util.Event,
        CUSTOM_CONTROL_NAMES = ["quota", "maxftp", "maxsql", "maxpop", "maxlst", "maxsub", "bwlimit", "maxpark", "maxaddon", "max_email_per_hour", "max_defer_fail_percentage", "max_emailacct_quota", "max_team_users"],
        mainForm = document.mainform,
        isNumeric = /^\d+$/,
        customControls = [];

    var MAX_USERNAME_LENGTH = 16;

    // this value gets altered only when the *user* sets a nonempty username;
    // if Javascript sets the username, then it doesn't get set
    var Custom_Username = false;

    var resetacctform = function() {

        var offlist = [mainForm.ip, mainForm.hasshell, mainForm.cgi];

        // resellers don't have this element
        if (DOM.inDocument("manual")) {
            if (DOM.get("manual").checked) {
                var offlistLength = offlist.length;
                for (var i = 0; i < offlistLength; i++) {
                    offlist[i].value = 1;
                }
            }
        }
    };

    /**
     * Massages related form values before submit.
     * @method checkacctform
     **/
    var checkacctform = function() {
        var offlist = [mainForm.ip, mainForm.hasshell];

        var savepkgCheckbox = DOM.get("pkgchkbox");

        // resellers don't have this element
        if (DOM.inDocument("manual")) {
            if (DOM.get("manual").checked) {
                for (var i = 0; i < offlist.length; i++) {
                    if (offlist[i] && !offlist[i].checked) {
                        offlist[i].checked = true;
                        offlist[i].value = 0;
                    }
                }
            } else if (savepkgCheckbox) {
                savepkgCheckbox.checked = false;
            }
        }

        var cgi = mainForm.cgi;
        if (!cgi.checked) {
            cgi.checked = true;
            cgi.value = 0;
        }

        // if save package checkbox is not checked
        // clear any value in the package name field
        // so it won't be displayed on results page

        if (savepkgCheckbox && savepkgCheckbox.checked === false) {
            var pkgNameField = DOM.get("pkgname");
            if (pkgNameField) {
                pkgNameField.value = "";
            }
        }

        // check the custom controls and massage the
        // fields so that only the name/value pair
        // gets submitted with the form
        var customControlNamesLength = CUSTOM_CONTROL_NAMES.length;
        for (var k = 0; k < customControlNamesLength; k++) {
            var controlPrefix = CUSTOM_CONTROL_NAMES[k];
            var customRadioEl = mainForm[controlPrefix + "_custom_radio"];
            var unlimitedRadioEl = mainForm[controlPrefix + "_unlimited_radio"];
            var textBoxEl = mainForm[controlPrefix];
            if (unlimitedRadioEl && unlimitedRadioEl.checked) {
                if (textBoxEl) {
                    textBoxEl.value = "unlimited";
                    textBoxEl.disabled = false;
                }
                unlimitedRadioEl.name = "";
            }
            if (customRadioEl) {
                customRadioEl.name = "";
            }
        }
    };

    var parsexmlnslist = function(o) {
        var nslist = o.responseText.split(":");
        var nstxt = nslist.join("<br />");
        DOM.get("nstouse").innerHTML = nstxt;
    };

    var ajaxnslist = function() {
        var domain = mainForm.domain.value;
        var useregns = mainForm.useregns.checked ? 1 : 0;

        DOM.get("nstouse").innerHTML = LOCALE.maketext("Updating …");

        var statcallback = {
            success: parsexmlnslist,
        };
        var sUrl = window.PAGE.nsListUrlPrefix + domain + "&useregns=" + useregns;
        YAHOO.util.Connect.asyncRequest("GET", sUrl, statcallback, null);
    };

    var dologinname = function() {
        if (mainForm.username.value === "" && !Custom_Username) {
            var domain = mainForm.domain.value;
            var username = domain.replace(/^\d+/, "").replace(/\.[^.]+$/, "").replace(/[^A-Za-z0-9]/g, "").substring(0, MAX_USERNAME_LENGTH);
            username = username.toLowerCase();
            mainForm.username.value = username;
        }
    };

    var fixaddress = function() {
        mainForm.domain.value = mainForm.domain.value.toLowerCase();
        mainForm.dbuser.value = mainForm.username.value;
    };

    var setnoplan = function() {
        mainForm.msel.selectedIndex = 0;
    };

    /**
     * Fix the custom resource setting manual control to the proper state.
     * @method fixCustomControl
     * @param {String} prefix the control base name.
     * @param {String} defaultValue the initial setting for the control
     **/
    var fixCustomControl = function(prefix, defaultValue) {
        var textControl = mainForm[prefix];
        var customRadio = mainForm[prefix + "_custom_radio"];
        var unlimitedRadio = mainForm[prefix + "_unlimited_radio"];
        if (textControl && isNumeric.test(defaultValue)) {
            textControl.value = defaultValue;
            if (customRadio) {
                customRadio.checked = true;
            }
            textControl.disabled = false;
        } else if (unlimitedRadio) {
            unlimitedRadio.checked = true;
            if (textControl) {
                textControl.disabled = true;
                textControl.value = textControl.defaultValue;
            }
        }
    };

    /**
     * Checks if an element with a given ID is hidden.
     * @param  {String}  elemId   The element ID in question.
     * @return {Boolean}          True when the element associated with the ID is hidden.
     */
    var isHidden = function(elemId) {
        return DOM.hasClass(elemId, "hidden");
    };

    /**
     * Aligns the Smart_Disable_Overlay div for each Grouped_Input_Set. The overlays
     * use absolute positioning relative to the entire #contentContainer, so they need
     * to be re-aligned any time the visible content changes.
     */
    var _alignCustomControls = function() {
        if (isHidden("mansettings")) {
            return;
        }

        customControls.forEach(function(customControl) {
            customControl.align();
        });
    };

    /**
     * The throttled version of _alignCustomControls. We can have many showHideDiv calls
     * in succession, so this ensures that we only run the function once per render cycle.
     */
    var alignCustomControls = function() {
        if (alignCustomControls.isQueued) {
            return;
        }

        alignCustomControls.isQueued = true;

        requestAnimationFrame(function() {
            alignCustomControls.isQueued = false;
            setTimeout(_alignCustomControls, 0);
        });
    };

    /**
     * Advanced version of showHideDiv that takes a custom canShow function.
     *
     * @param  {Element}  divName Element to show/hide based on the results of the canShow method.
     * @param  {Function} canShow That returns true when the element passed to showHideDiv should
     *                            be shown and false when the div element should be hidden
     */
    var showHideDivAdvanced = function(divName, canShow) {
        if (!canShow || typeof canShow !== "function") {
            throw new Error("Failed to pass the canShow function for " + divName + " processing.");
        }
        if (DOM.get(divName)) {
            if (canShow() === true) {
                DOM.removeClass(divName, "hidden");
            } else {
                DOM.addClass(divName, "hidden");
            }

            alignCustomControls();
        }
    };

    /**
     * Factory to generate a canShow() function for a single checkbox element.
     *
     * @param  {CheckboxInputElement} checkboxEl
     * @return {Function}            That returns true when the div element passed to showHideDiv
     *                               should be shown and false when the div element should be hidden
     */
    var canShowFactory = function( checkboxEl ) {
        return function() {
            if (checkboxEl.checked === true) {
                return true;
            }
            return false;
        };
    };

    /**
     * Toggles the visibility of the given div based on the state of a particular
     * input control.
     * @method showHideDiv
     * @param {String} divName the name of the div to be shown/hidden
     * @param {String|Element} checkboxInput the control whose state determines whether the div is shown/hidden
     **/
    var showHideDiv = function(divName, checkboxInput) {
        var checkboxEl = DOM.get(checkboxInput);
        if (!checkboxEl) {
            return;
        }

        showHideDivAdvanced(divName, canShowFactory(checkboxEl));
    };

    /*
     * Adds "last" class to last property editor within a property group.
     * Makes sure last property editor doesn't have a bottom border
     * (primarily for IE8 compatibility).
     * Called from onDOMReady
     *
     * @method addLastStyleToPropertyGroups
     */
    var addLastStyleToPropertyGroups = function() {
        var packageExtensions = DOM.getElementsByClassName("propertyGroup", "div", "packageExtensions");

        var isLastPropertyEditor = function(el) {
            return DOM.hasClass(el, "propertyEditor");
        };

        var propertyGroupCount = packageExtensions.length;
        for (var j = 0; j < propertyGroupCount; j++) {
            var lastInGroup = DOM.getLastChildBy(packageExtensions[j], isLastPropertyEditor);
            if (lastInGroup) {
                DOM.addClass(lastInGroup, "last");
            }
        }
    };

    var getExtensionFormSuccess = function(args) {
        var extensionsDiv = DOM.get("packageExtensions");
        if (args.cpanel_data.html) {
            extensionsDiv.innerHTML = args.cpanel_data.html.trim();
        } else {
            extensionsDiv.innerHTML = "";
        }
        showHideDiv("packageExtensions", "manual");

        addLastStyleToPropertyGroups();
    };

    var getExtensionFormFailure = function(args) {
        var extensionsDiv = DOM.get("packageExtensions");
        extensionsDiv.innerHTML = "";
        showHideDiv("packageExtensions", "manual");
    };

    /**
     * Fixes the displayed values on the form in response to package change.
     *
     * @method updateform
     * @param {String} nfo comma-delimited list of package values.
     */
    var updateform = function(nfo) {
        var selectEl = mainForm.msel;
        selectEl.className = selectEl.options[selectEl.selectedIndex].className;
        var cpsets = nfo.split(",");

        if (mainForm.plan) {
            if (cpsets[23]) {
                mainForm.plan.value = cpsets[23];
            } else {
                mainForm.plan.value = "";
            }
        }
        var pkgSystemDefaultValues = PAGE.packageSystemDefaultValues;

        // ip,cgi,quota,cp,maxftp,maxsql,maxpop,maxlst,maxsub,plan,maxpark,maxaddon

        /*
         * NOTE NOTE NOTE! You should update any code relating to cpsets if you
         * *ever* add any parameters to wwwacct, otherwise you'll have a bad
         * time!
         *
         * Check the order in Whostmgr::Packages::Legacy
         */

        var ipCheckbox = mainForm.ip;
        if (ipCheckbox) {

            // Get system default if the provided value is empty.
            var hasDedicatedIp = getResourceValue(cpsets[0], pkgSystemDefaultValues["ip"], mainForm.plan.value);
            if (hasDedicatedIp === "n") {
                ipCheckbox.checked = false;
            } else {
                ipCheckbox.checked = true;
            }
            showHideDiv("ipselect", "ipchkbox");
        }

        var spf_check = DOM.get("spf");
        if (spf_check) {
            var template_to_use = (cpsets[0] === "n" ? "standardvirtualftp" : "standard");
            var zone_template_spf = window.PAGE.ZONE_TEMPLATE_SPF[template_to_use];
            if (zone_template_spf) {
                spf_check.checked = spf_check.disabled = true;
                DOM.addClass("spf_label", "disabled");
                var link = DOM.get("zone_template_link");
                link.href = link.href.replace(/(template=)[^&]*/, "$1" + template_to_use);
                CPANEL.util.set_text_content("zone_template_spf_string", zone_template_spf);
            } else {
                spf_check.disabled = false;
                spf_check.checked = window.PAGE.spf_checked;
                DOM.removeClass("spf_label", "disabled");
            }
        }

        // Get system default if the provided value is empty.
        var hasCgiAccess = getResourceValue(cpsets[1], pkgSystemDefaultValues["cgi"], mainForm.plan.value);
        if (hasCgiAccess === "n") {
            mainForm.cgi.checked = false;
        } else {
            mainForm.cgi.checked = true;
        }

        fixCustomControl("quota", getResourceValue(cpsets[2], pkgSystemDefaultValues["quota"], mainForm.plan.value));
        fixCustomControl("bwlimit", getResourceValue(cpsets[10], pkgSystemDefaultValues["bwlimit"], mainForm.plan.value));
        fixCustomControl("maxftp", getResourceValue(cpsets[5], pkgSystemDefaultValues["maxftp"], mainForm.plan.value));
        fixCustomControl("maxsql", getResourceValue(cpsets[6], pkgSystemDefaultValues["maxsql"], mainForm.plan.value));
        fixCustomControl("maxpop", getResourceValue(cpsets[7], pkgSystemDefaultValues["maxpop"], mainForm.plan.value));
        fixCustomControl("maxlst", getResourceValue(cpsets[8], pkgSystemDefaultValues["maxlst"], mainForm.plan.value));
        fixCustomControl("maxsub", getResourceValue(cpsets[9], pkgSystemDefaultValues["maxsub"], mainForm.plan.value));

        fixCustomControl("maxpark", getResourceValue(cpsets[12], pkgSystemDefaultValues["maxpark"], mainForm.plan.value));
        fixCustomControl("maxaddon", getResourceValue(cpsets[13], pkgSystemDefaultValues["maxaddon"], mainForm.plan.value));
        fixCustomControl("max_email_per_hour", getResourceValue(cpsets[16], pkgSystemDefaultValues["max_email_per_hour"], mainForm.plan.value));
        fixCustomControl("max_defer_fail_percentage", getResourceValue(cpsets[17], pkgSystemDefaultValues["max_defer_fail_percentage"], mainForm.plan.value));
        fixCustomControl("max_emailacct_quota", getResourceValue(cpsets[20], pkgSystemDefaultValues["max_emailacct_quota"], mainForm.plan.value));
        fixCustomControl("maxpassengerapps", getResourceValue(cpsets[21], pkgSystemDefaultValues["maxpassengerapps"], mainForm.plan.value));
        fixCustomControl("max_team_users", getResourceValue(cpsets[22], pkgSystemDefaultValues["max_team_users"], mainForm.plan.value));

        if (mainForm.hasshell) {

            // Get system default if the provided value is empty.
            var hasShellAccess = getResourceValue(cpsets[11], pkgSystemDefaultValues["hasshell"], mainForm.plan.value);
            if (hasShellAccess === "n") {
                mainForm.hasshell.checked = false;
            } else {
                mainForm.hasshell.checked = true;
            }
        }

        var i = 0;

        if (mainForm.cpmod) {

            // Get system default if the provided value is empty.
            var cpThemeValue = getResourceValue(cpsets[4], pkgSystemDefaultValues["cpmod"], mainForm.plan.value);
            for (i = 0; i < mainForm.cpmod.options.length; i++) {
                if (mainForm.cpmod.options[i].value === cpThemeValue) {
                    mainForm.cpmod.selectedIndex = i;
                }
            }
        }

        if (mainForm.featurelist) {

            // Get system default if the provided value is empty.
            var defaultFeaturelist = getResourceValue(cpsets[14], pkgSystemDefaultValues["featurelist"], mainForm.plan.value);
            for (i = 0; i < mainForm.featurelist.options.length; i++) {
                if (mainForm.featurelist.options[i].value === defaultFeaturelist) {
                    mainForm.featurelist.selectedIndex = i;
                }
            }
        }
        if (mainForm.language) {

            // Get system default if the provided value is empty.
            var defaultLanguage = getResourceValue(cpsets[15], pkgSystemDefaultValues["language"], mainForm.plan.value);
            for (i = 0; i < mainForm.language.options.length; i++) {
                if (mainForm.language.options[i].value === defaultLanguage) {
                    mainForm.language.selectedIndex = i;
                }
            }
        }

        // cpsets[18] used to be the removed max_defer_fail_min_trigger
        // Get system default if the provided value is empty.
        var defaultDigestAuthSetting = getResourceValue(cpsets[19], pkgSystemDefaultValues["digestauth"], mainForm.plan.value);
        if (defaultDigestAuthSetting === "n") {
            mainForm.digestauth.checked = false;
        } else {
            mainForm.digestauth.checked = true;
        }

        if (cpsets[23]) {
            CPANEL.api({
                application: "whm",
                func: "_getpkgextensionform",
                data: {
                    pkg: cpsets[23],
                },
                callback: {
                    success: getExtensionFormSuccess,
                    failure: getExtensionFormFailure,
                },
            });
        } else {
            var pkgExtDiv = DOM.get("packageExtensions");
            pkgExtDiv.innerHTML = "";
        }

    };

    var getResourceValue = function(resourceValue, systemDefValue, plan) {
        if (resourceValue) {
            return resourceValue;
        }
        if ((!plan || plan === "default") && !resourceValue) {

            // Assign the system default value if the resource is isn't set by a plan.
            return systemDefValue;
        } else {
            return resourceValue;
        }
    };

    var js_upgrade = function() {
        showHideDiv("ipselect", "ipchkbox");
        showHideDiv("resellown", "resell");
        var mansettingsEl = DOM.get("mansettings");
        if (mansettingsEl) {
            DOM.addClass(mansettingsEl, "hidden");
        }
    };

    var validPackageSelected = function() {
        var pkgSelectEl = DOM.get("pkgselect");
        if (pkgSelectEl && pkgSelectEl.value === "---") {
            return false;
        }
        return pkgSelectEl.selectedIndex >= 0;
    };

    var username_length = function() {
        var username = DOM.get("username").value;

        if (!username) {
            return false;
        }

        return CPANEL.validate.max_length(username, MAX_USERNAME_LENGTH);
    };

    var user_not_pw = function() {
        var user = DOM.get("username").value;
        var pw = DOM.get("password").value;
        if (user.toLowerCase() === pw.toLowerCase()) {
            return false;
        }
        return true;
    };

    var username_stupidstuff = function() {
        if (window.PAGE.ALLOWSTUPIDSTUFF === 1) {
            return true;
        }

        var username = DOM.get("username").value;
        return !username || CPANEL.validate.alpha(username.charAt(0));
    };

    var username_tolowercase = function() {
        DOM.get("username").value = DOM.get("username").value.toLowerCase();
    };

    var force_pkgname_validation = 0;
    var add_new_validation = function() {
        var valid_username = function() {
            var value = document.getElementById("username").value;
            return (new RegExp(window.PAGE.username_regexp)).test(value);
        };

        VALID.domain = new CPANEL.validate.validator(LOCALE.maketext("Domain"));
        VALID.domain.add("domain", "fqdn", LOCALE.maketext("This is not a valid domain."));
        VALID.domain.attach();

        var valid_pkgname = function() {

            // only validate if the value will be used
            if (!force_pkgname_validation) {
                if (!document.getElementById("pkgchkbox").checked || !document.getElementById("manual").checked) {
                    return true;
                }
            }

            var svname = document.getElementById("pkgname").value;

            // The window.PAGE.pkgname_regexp approach is complicated (need to adjust template, whostmgr/bin/whostmgr5.pl, and create a get_regexp function w/ tests).
            //    Even then its not flexible enough since its tricky to do this-but-not-that matches in one regexp.
            // The logic below is based on what Whostmgr::Packages::Mod::_modpkg does with $name.
            if (svname === null || svname.length === 0) {
                return false;
            }
            if (/\.\./.test(svname)) {
                return false;
            }
            if (svname === "undefined" || svname === "extensions") {
                return false;
            }
            if (/[^a-zA-z0-9.\- _]/.test(svname)) {
                return false;
            }

            return true;
        };

        if (DOM.get("pkgname")) {
            VALID.pkgname = new CPANEL.validate.validator(LOCALE.maketext("Package Name"));
            VALID.pkgname.add("pkgname", valid_pkgname, LOCALE.maketext("This is not a valid package name."));
            VALID.pkgname.attach();
        }
        VALID.username = new CPANEL.validate.validator(LOCALE.maketext("Username"));
        VALID.username.add("username", "no_chars(%input%,' ')", LOCALE.maketext("A username cannot contain spaces."));
        VALID.username.add("username", username_length, LOCALE.maketext("A username must have between [numf,_1] and [quant,_2,character,characters].", 1, MAX_USERNAME_LENGTH));
        VALID.username.add("username", username_stupidstuff, LOCALE.maketext("A username must start with a letter."));
        VALID.username.add("username", user_not_pw, LOCALE.maketext("The username cannot be the same as the password."));
        VALID.username.add("username", valid_username, LOCALE.maketext("This is not a valid username."));

        VALID.username.attach();
        var password_validators = CPANEL.password.setup("password", "password2", "password_strength", window.PAGE.REQUIRED_PASSWORD_STRENGTH, "create_strong_password", "why_strong_passwords_link", "why_strong_passwords_text");
        VALID.pass1 = password_validators[0];
        VALID.pass2 = password_validators[1];

        // The contact email is optional. We will indicate that it is optional by only
        // showing a validation error if the field has text in it and the text is not a valid
        // email address.
        VALID.email_validator = new CPANEL.validate.validator(LOCALE.maketext("Email"));
        VALID.email_validator.add("contactemail", "if_not_empty(%input%, CPANEL.validate.email)", LOCALE.maketext("The email field must be empty or an email address."));
        VALID.email_validator.attach();

        // if this is a reseller creating an account and the reseller does not have the "edit-account"
        // privilege, the reseller must select a package (the first package, "---", is not valid!)
        if (!window.PAGE.editaccount) {
            VALID.pkg = new CPANEL.validate.validator(LOCALE.maketext("Selected Package"));
            VALID.pkg.add("pkgselect", validPackageSelected, LOCALE.maketext("You must select a package."));
            VALID.pkg.attach();
        } else {

            /**
             * The edit-account privilege allows us to manually set limits on an account
             * and bypass limits on a given package. The manual resource option inputs are
             * only included in the template with this privilege level.
             */

            VALID.manual_resource_options = new CPANEL.validate.validator(LOCALE.maketext("Manual Resource Options"));

            [

                // id, minimum validation message, minimum value
                [ "quota", LOCALE.maketext("You must enter a value of 1 or greater."), 1 ],
                [ "bwlimit", LOCALE.maketext("You must enter a value of 1 or greater."), 1 ],
                [ "maxftp", LOCALE.maketext("You must enter a value of 0 or greater."), 0 ],
                [ "maxpop", LOCALE.maketext("You must enter a value of 0 or greater."), 0 ],
                [ "maxlst", LOCALE.maketext("You must enter a value of 0 or greater."), 0 ],
                [ "maxsql", LOCALE.maketext("You must enter a value of 0 or greater."), 0 ],
                [ "maxsub", LOCALE.maketext("You must enter a value of 0 or greater."), 0 ],
                [ "maxpark", LOCALE.maketext("You must enter a value of 0 or greater."), 0 ],
                [ "maxaddon", LOCALE.maketext("You must enter a value of 0 or greater."), 0 ],
                [ "max_email_per_hour", LOCALE.maketext("You must enter a value of 0 or greater."), 0 ],
            ].forEach(function(v) {
                var item = v[0];
                var message = v[1];
                VALID.manual_resource_options.add(item, "min_value(%input%, " + v[2] + ")", message);
            });

            VALID.manual_resource_options.add("max_emailacct_quota", "min_value(%input%, 1)", LOCALE.maketext("You must enter a value of 1 or greater."));

            var quota_max = "max_value(%input%, " + window.PAGE.max_email_quota_mib + ")";
            VALID.manual_resource_options.add("max_emailacct_quota", quota_max, LOCALE.maketext("You must enter a value of less than or equal to [_1].", window.PAGE.max_email_quota_mib));

            VALID.manual_resource_options.add("max_defer_fail_percentage", function() {
                var vStr = DOM.get("max_defer_fail_percentage").value;
                var vNum = parseInt(vStr, 10);
                return vNum >= 1 && vNum <= 100;
            }, LOCALE.maketext("You must enter a value between 1 and 100."));

            VALID.manual_resource_options.attach();
        }

        if (DOM.get("max_team_users_field")) {
            var valid_max_team_users = function() {
                var max_team_users_field = DOM.get("max_team_users_field").value.trim();

                if (!max_team_users_field) {
                    return false;
                }

                max_team_users_field = max_team_users_field.split(/[\s;,]+/);
                if (max_team_users_field.length > 2) {
                    return false;
                }

                if (max_team_users_field < 0 || max_team_users_field > window.PAGE.SERVER_MAX_TEAM_USERS) {
                    return false;
                }

                return true;
            };
            // eslint-disable-next-line new-cap
            VALID["max_team_users_field"] = new CPANEL.validate.validator(
                LOCALE.maketext("Max Team Users")
            );
            VALID["max_team_users_field"].add(
                "max_team_users_field",
                valid_max_team_users,
                LOCALE.maketext(
                    "The input must be a number between “[_1]” and “[_2]”.",
                    0,
                    window.PAGE.SERVER_MAX_TEAM_USERS
                )
            );
            VALID["max_team_users_field"].attach();
        }

        CPANEL.validate.attach_to_form("submit", VALID);
    };

    var toggle_reseller_options = function() {
        var chkResell      = DOM.get("resell");
        var chkOwnerSelf   = DOM.get("ownerself");
        var labelOwnerSelf = chkOwnerSelf.parentElement;

        if (chkResell.checked) {
            chkOwnerSelf.disabled = false;
            DOM.removeClass(labelOwnerSelf, "disabled");
        } else {
            chkOwnerSelf.disabled = true;
            chkOwnerSelf.checked = false;
            DOM.addClass(labelOwnerSelf, "disabled");
        }
    };

    var init_page = function() {

        if (!mainForm) {
            mainForm = document.mainform;
        }

        /* On cPanel SOLO, it still won't exist. Just return if we can't ever get the mainform. */
        if (!mainForm) {
            return;
        }

        // set up custom controls for manually configured package settings
        // if needed.
        var controlNamesLength = CUSTOM_CONTROL_NAMES.length;
        for (var i = 0; i < controlNamesLength; i++) {
            if (document.getElementById(CUSTOM_CONTROL_NAMES[i] + "_custom_radio")) {
                customControls.push(new CPANEL.ajax.Grouped_Input_Set(document.forms.mainform, CUSTOM_CONTROL_NAMES[i] + "_custom_radio", CUSTOM_CONTROL_NAMES[i] + "_unlimited_radio"));
            }
        }

        EVENT.on("domain", "blur", function() {
            dologinname();
            VALID.username.verify();
        });

        EVENT.on("domain", "change", function() {
            ajaxnslist();
            fixaddress();
        });

        EVENT.on("username", "blur", fixaddress);

        EVENT.on("username", "change", function() {
            Custom_Username = DOM.get("username").value !== "";
        });

        EVENT.on("mainform", "submit", checkacctform);

        EVENT.on("pkgselect", "change", function() {
            var pkgSelectEl = DOM.get("pkgselect");
            var nfo = pkgSelectEl.options[pkgSelectEl.selectedIndex].value;
            updateform(nfo);
        });

        // automatically convert username to lower case
        EVENT.on("username", "change", username_tolowercase);

        EVENT.on("manual", "change", function() {
            showHideDiv("manoptions", "manual");
            showHideDiv("mansettings", "manual");

            // packageExtensions
            showHideDiv("packageExtensions", "manual");

            var inputEl = DOM.get("manual");
            var saveAsPkgEl = DOM.get("pkgchkbox");
            var manOptsEl = DOM.get("manualOptionsEditor");
            var pkgNameEl = DOM.get("pkgname");

            // remove or restore separator line as
            // necessary. Make sure the package
            // checkbox is correctly checked

            if (manOptsEl && inputEl && inputEl.checked === true) {
                DOM.removeClass(manOptsEl, "last");
                DOM.addClass("mansettings1", "last");
            } else if (manOptsEl && inputEl) {
                DOM.addClass(manOptsEl, "last");
            }

            // extra settings settings
            showHideDiv("dedicatedIp", "manual");
            showHideDiv("allowShell", "manual");
            showHideDiv("allowCGI", "manual");
            showHideDiv("allowDigest", "manual");

            // extra package settings
            showHideDiv("mansettings1", "manual"); // save manual settings as a package
            if (saveAsPkgEl && saveAsPkgEl.checked === true) {
                DOM.removeClass("mansettings1", "last");
                showHideDiv("pkgNameEditor", "manual"); // package name
                showHideDiv("featureListEditor", "manual"); // feature list dropdown
                showHideDiv("pkgname_error_panel", "manual"); // package name validation message
                showHideDiv("pkgname_error", "manual");
                if (pkgNameEl) {
                    force_pkgname_validation = 1;
                    VALID.pkgname.verify(); // there is no .validate()
                    force_pkgname_validation = 0;
                }
            }

            CUSTOM_CONTROL_NAMES.forEach( function(control) {
                var chkManualEl = DOM.get("manual");
                var chkEl       = DOM.get(control + "_custom_radio");

                /**
                 * Factory function that enforces the parent/child heirarcy for the manual/manual resource
                 * options sections.
                 *
                 * @param  {CheckboxInputElement} chkManualEl Parent control
                 * @param  {CheckboxInputElement} chkEl       Dependent control
                 * @return {Function}             That returns true when the element should be shown and false when it should not be shown.
                 */
                var _canShowFactory = function(chkManualEl, chkEl) {
                    return function() {
                        if (chkManualEl.checked !== true) {

                            // Manual Options section is not shown
                            return false;
                        } else if (chkEl.checked === true) {
                            return true;
                        } else {
                            return false;
                        }
                    };
                };
                var _canCheck = _canShowFactory(chkManualEl, chkEl);

                showHideDivAdvanced(control + "_error", _canCheck);
                showHideDivAdvanced(control + "_error_panel", _canCheck);
            });

        });

        /* Hide validation error messages if the field with the invalid value is not selected (and unlimited is selecetd instead) */
        CUSTOM_CONTROL_NAMES.forEach( function(control) {
            var action = function() {
                var chkEl = DOM.get(control + "_custom_radio");
                showHideDiv(control + "_error", chkEl);
                showHideDiv(control + "_error_panel", chkEl);
            };

            EVENT.on(control + "_custom_radio", "change", action);
            EVENT.on(control, "focus", action); // Needed because clicking in the text box for some reason doesn't fire a ..._custom_radio change event
            EVENT.on(control + "_unlimited_radio", "change", action);

            EVENT.on(control, "paste", function(e) {
                var pastedText = e.clipboardData.getData("text");
                if (pastedText.match(/[^0-9]/)) {
                    e.preventDefault();
                }
            });

        });

        EVENT.on("pkgchkbox", "change", function() {
            var saveAsPkgEl = DOM.get("pkgchkbox");
            if (saveAsPkgEl && saveAsPkgEl.checked === true) {
                DOM.removeClass("mansettings1", "last");
            } else {
                DOM.addClass("mansettings1", "last");
            }

            showHideDiv("pkgNameEditor", "pkgchkbox"); // package name

            showHideDiv("featureListEditor", "pkgchkbox"); // feature list dropdown
            showHideDiv("pkgname_error_panel", "pkgchkbox"); // package name validation message
            showHideDiv("pkgname_error", "pkgchkbox");

            if (DOM.hasClass("pkgNameEditor", "hidden") && VALID.pkgname) {
                VALID.pkgname.detach();
            } else if (VALID.pkgname) {
                VALID.pkgname.attach();
                force_pkgname_validation = 1;
                VALID.pkgname.verify(); // there is no .validate()
                force_pkgname_validation = 0;
            }
        });

        EVENT.on("resell", "click", toggle_reseller_options);

        var manSettingControls = DOM.getElementsByClassName("manualOption", "input", "mansettings");

        EVENT.on(manSettingControls, "change", setnoplan);

        EVENT.on("useregns", "click", ajaxnslist);
        EVENT.on("ipchkbox", "click", function() {
            showHideDiv("ipSelect", "ipchkbox");
        });

        EVENT.on("spamassassin", "change", function() {

            var spambox = DOM.get("spambox");

            if ( DOM.get("spamassassin").checked ) {
                spambox.disabled = false;
                spambox.title = "";
                DOM.removeClass("spambox_label", "disabled");
            } else {
                spambox.disabled = true;
                spambox.title = LOCALE.maketext("You must enable [asis,Apache SpamAssassin™] to use the Spam Box feature.");
                DOM.addClass("spambox_label", "disabled");
            }

        });

        var helpPanel;
        EVENT.on("spambox_help", "mouseover", function() {

            if ( !DOM.get("spamassassin").checked ) {
                return;
            }

            if ( !helpPanel ) {

                helpPanel = new YAHOO.widget.Panel("spambox_help_panel", {
                    width: "250px",
                    fixedcenter: false,
                    draggable: false,
                    modal: false,
                    visible: false,
                    close: false,
                });

                helpPanel.setHeader(LOCALE.maketext("Enable Spam Box"));
                helpPanel.cfg.setProperty("context", [DOM.get("spambox_help"), "tl", "br"]);
                helpPanel.setBody(DOM.get("spambox_help_content"));
                helpPanel.render(DOM.get("spambox_help"));

                DOM.get("spambox_help_content").style = "";
            }

            helpPanel.show();
        });

        EVENT.on("spambox_help", "mouseout", function() {

            if ( helpPanel ) {
                helpPanel.hide();
            }

        });

        // update nameservers
        ajaxnslist();

        // add validation
        add_new_validation();

        dologinname();
        document.getElementById("username").value = "";
        updateform(document.mainform.msel.options[document.mainform.msel.selectedIndex].value);

        resetacctform();
        js_upgrade(); // warning, this function can return nothing and stop execution of this function
        // temporary fix: put it at the bottom

        // force the select options manually off on a page reload

        var manualCheckbox = DOM.get("manual");
        if (manualCheckbox) {
            manualCheckbox.checked = false;
        }

        // Submit button is initially enabled
        var submitButton = DOM.get("submit");
        if (submitButton) {
            submitButton.disabled = false;
        }
    };

    EVENT.onDOMReady(init_page);

}());
Back to Directory File Manager