Difference between revisions of "MediaWiki:Gadget-calculator-core.js"

From WikiAnesthesia
 
(85 intermediate revisions by the same user not shown)
Line 14: Line 14:


     var DEFAULT_CALCULATION_CLASS = 'SimpleCalculation';
     var DEFAULT_CALCULATION_CLASS = 'SimpleCalculation';
     var DEFAULT_CALCULATOR_CLASS = 'SimpleCalculator';
 
     // Polyfill to convert to roman numerals
    math.roman = function( number ) {
        var romanOrders = {
            M: 1000,
            CM: 900,
            D: 500,
            CD: 400,
            C: 100,
            XC: 90,
            L: 50,
            XL: 40,
            X: 10,
            IX: 9,
            V: 5,
            IV: 4,
            I: 1
        };
 
        var roman = '';
 
        for( var iOrder in romanOrders ) {
            var numOfOrder = Math.floor(number / romanOrders[ iOrder ] );
            number -= numOfOrder * romanOrders[ iOrder ];
            roman += iOrder.repeat( numOfOrder );
        }
 
        return roman;
    };


     // Polyfill to fetch unit's base. This may become unnecessary in a future version of math.js
     // Polyfill to fetch unit's base. This may become unnecessary in a future version of math.js
Line 29: Line 57:


     mw.calculators = {
     mw.calculators = {
        calculators: {},
         calculations: {},
         calculations: {},
         objectClasses: {},
         objectClasses: {},
        options: {},
        selectors: {
            calculationCategories: '.calculator-calculationcategory',
            calculations: '.calculator-calculation',
            calculatorOptions: '.calculator-options'
        },
         units: {},
         units: {},
         unitsBases: {},
         unitsBases: {},
Line 46: Line 79:


                 mw.calculators.calculations[ calculationId ].setDependencies();
                 mw.calculators.calculations[ calculationId ].setDependencies();
            }
        },
        addCalculators: function( moduleId, calculatorData, className ) {
            className = className ? className : DEFAULT_CALCULATOR_CLASS;
            for( var calculatorId in calculatorData ) {
                calculatorData[ calculatorId ].module = moduleId;
                // Make sure the calculations have been defined
                for( var iCalculation in calculatorData[ calculatorId ].calculations ) {
                    var calculationId = calculatorData[ calculatorId ].calculations[ iCalculation ];
                    if( !mw.calculators.getCalculation( calculationId ) ) {
                        throw new Error( 'Calculator "' + calculatorId + '" references calculation "' + calculationId + '" which is not defined' );
                    }
                }
            }
            var calculators = mw.calculators.createCalculatorObjects( className, calculatorData );


            // Initalize the calculators property for the module
                 mw.calculators.calculations[ calculationId ].update();
            if( !mw.calculators.calculators.hasOwnProperty( moduleId ) ) {
                 mw.calculators.calculators[ moduleId ] = {};
            }
 
            // Store the calculators
            for( var calculatorId in calculators ) {
                mw.calculators.calculators[ moduleId ][ calculatorId ] = calculators[ calculatorId ];
 
                mw.calculators.calculators[ moduleId ][ calculatorId ].render();
             }
             }
         },
         },
Line 82: Line 87:


             for( var unitsBaseId in unitsBases ) {
             for( var unitsBaseId in unitsBases ) {
                 mw.calculators.unitsBases[ unitsBaseId ] = unitsBases[ unitsBaseId ];
                 mw.calculators.unitsBases[ unitsBaseId.toLowerCase() ] = unitsBases[ unitsBaseId ];
             }
             }
         },
         },
Line 107: Line 112:
                 }
                 }


                 mw.calculators.units[ units ] = units[ unitsId ];
                 mw.calculators.units[ unitsId ] = units[ unitsId ];
             }
             }
         },
         },
Line 150: Line 155:
             return objects;
             return objects;
         },
         },
         createInputGroup: function( variableIds, global ) {
         createInputGroup: function( variableIds, global, maxInputsPerRow ) {
             var $form = $( '<form>', {
             var $form = $( '<form>', {
                 novalidate: true
                 novalidate: true
             } );
             } );


             var $formRow = $( '<div>', {
             var $formRow;
                class: 'form-row'
            } ).css( 'flex-wrap', 'nowrap' );


             var inputOptions = {
             var inputOptions = {
                 global: !!global
                 global: !!global
             };
             };
            maxInputsPerRow = maxInputsPerRow ?
                maxInputsPerRow :
                mw.calculators.getOptionValue( 'inputgroupmaxinputsperrow' );
            var inputCount = 0;


             for( var iVariableId in variableIds ) {
             for( var iVariableId in variableIds ) {
Line 168: Line 177:
                 if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                 if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                     throw new Error( 'Invalid variable name "' + variableId + '"' );
                     throw new Error( 'Invalid variable name "' + variableId + '"' );
                }
                if( inputCount % maxInputsPerRow === 0 ) {
                    if( $formRow ) {
                        $form.append( $formRow );
                    }
                    $formRow = $( '<div>', {
                        class: 'form-row calculator-inputGroup'
                    } );
                 }
                 }


                 $formRow.append( mw.calculators.variables[ variableId ].createInput( inputOptions ) );
                 $formRow.append( mw.calculators.variables[ variableId ].createInput( inputOptions ) );
                inputCount++;
             }
             }


Line 194: Line 215:
             }
             }
         },
         },
         getCalculator: function( moduleId, calculatorId ) {
         getOptionValue: function( optionId ) {
             if( mw.calculators.calculators.hasOwnProperty( moduleId ) &&
             return mw.calculators.options.hasOwnProperty( optionId ) ?
                 mw.calculators.calculators[ moduleId ].hasOwnProperty( calculatorId ) ) {
                 mw.calculators.options[ optionId ] :
                return mw.calculators.calculators[ moduleId ][ calculatorId ];
                 undefined;
            } else {
         },
                 return null;
            }
         },
         getUnitsByBase: function( value ) {
         getUnitsByBase: function( value ) {
             if( typeof value !== 'object' || !value.hasOwnProperty( 'units' ) ) {
             if( typeof value !== 'object' || !value.hasOwnProperty( 'units' ) ) {
Line 289: Line 307:


             if( absNumber >= 10 || absNumber === 0 ) {
             if( absNumber >= 10 || absNumber === 0 ) {
                 decimals = 0;
                 if( absNumber < 100 && absNumber !== math.round( absNumber ) && 2 * absNumber === math.round( 2 * absNumber ) ) {
                    // Special case to allow nearly-round decimals (e.g. 12.5)
 
                    decimals = 1;
                } else {
                    decimals = 0;
                }
             } else {
             } else {
                 decimals = -math.floor( math.log10( absNumber ) ) + 1;
                 decimals = -math.floor( math.log10( absNumber ) ) + 1;
Line 324: Line 348:


                     if( newSIUnit !== oldSIUnit ) {
                     if( newSIUnit !== oldSIUnit ) {
                         var newValue = math.unit( newSIValue.toNumber() + ' ' + value.formatUnits().replace( oldSIUnit, newSIUnit ) );
                         value = math.unit( newSIValue.toNumber() + ' ' + value.formatUnits().replace( oldSIUnit, newSIUnit ) );


                         valueNumber = mw.calculators.getValueNumber( newValue, decimals );
                         valueNumber = mw.calculators.getValueNumber( value, decimals );
                         valueUnits = mw.calculators.getUnitsString( newValue );
                         valueUnits = mw.calculators.getUnitsString( value );
                     }
                     }
                 }
                 }
Line 336: Line 360:
             if( valueUnits ) {
             if( valueUnits ) {
                 valueString += ' ' + valueUnits;
                 valueString += ' ' + valueUnits;
            }
            var unitsId = value.formatUnits();
            if( mw.calculators.units.hasOwnProperty( unitsId ) &&
                typeof mw.calculators.units[ unitsId ].formatValue === 'function' ) {
                valueString = mw.calculators.units[ unitsId ].formatValue( valueString );
             }
             }


Line 356: Line 387:
         },
         },
         initialize: function() {
         initialize: function() {
             $( '.calculator' ).each( function() {
            // Change the menu item from "article" to "calculator"
                var gadgetModule = 'ext.gadget.calculator-' + $( this ).attr( 'data-module' );
             $( '#nav-article svg' ).addClass( 'fa-calculator' );
            $( '#nav-article .nav-label' ).html( 'Calculator' );


                if( gadgetModule && mw.loader.getState( gadgetModule ) === 'registered' ) {
            // Wrap description in a collapse
                     mw.loader.load( gadgetModule );
            var descriptionCount = 0;
 
            $( '.calculator-description' ).each( function() {
                var descriptionContainerId = 'calculator-description-info';
 
                if( descriptionCount ) {
                     descriptionContainerId += '-' + descriptionCount;
                 }
                 }
            } );
        },
        isMobile: function() {
            return window.matchMedia( 'only screen and (max-width: 760px)' ).matches;
        },
        isValueMathObject: function( value ) {
            return value && value.hasOwnProperty( 'value' );
        },
        prepareReferences: function( references ) {
            for( var iReference in references ) {
                var reference = references[ iReference ];


                 // Pubmed
                 var $descriptionLinkIcon = $( '<i>', {
                reference = reference.replace(
                     class: 'far fa-question-circle fa-fw'
                    /PMID: (\d+)/gm,
                 } );
                     'PMID: <a href=\'https://pubmed.ncbi.nlm.nih.gov/$1\'>$1</a>'
                 );


                 references[ iReference ] = reference;
                 var descriptionLinkString = '';
            }


            return references;
                descriptionLinkString += $( this ).data( 'title' ) ? $( this ).data( 'title' ) : 'About this calculator';
        },
 
        setCookieValue: function( variableId, value ) {
                var $descriptionLinkLabel = $( '<span>', {
            mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
                    html: descriptionLinkString
                expires: COOKIE_EXPIRATION
                } );
            } );
 
        },
                var $descriptionLink = $( '<a>', {
        setValue: function( variableId, value ) {
                    'data-toggle': 'collapse',
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                    href: '#' + descriptionContainerId,
                return false;
                    role: 'button',
            }
                    'aria-expanded': 'false',
                    'aria-controls': descriptionContainerId
                } ).append( $descriptionLinkIcon, $descriptionLinkLabel );


            if( !mw.calculators.variables[ variableId ].setValue( value ) ) {
                var $descriptionContainer = $( '<div>', {
                 return false;
                    id: descriptionContainerId,
            }
                    class: 'collapse calculator-description-info',
                    html: $( this ).html()
                 } );


            mw.calculators.setCookieValue( variableId, value );
                $( this ).empty();


            return true;
                if( !descriptionCount ) {
        },
                    $descriptionLink.addClass( 'dropdown-item' );
        uniqueValues: function( value, index, self ) {
                    $descriptionLinkLabel.addClass( 'nav-label' );
            return self.indexOf( value ) === index;
        }
    };


    /**
                    $('#menuButton .dropdown-menu').prepend( $descriptionLink );
    * Class CalculatorObject
                } else {
    *
                    $descriptionLink.addClass( 'btn btn-outline-primary btn-sm' );
    * @param {Object} properties
                    $( this ).append( $descriptionLink );
    * @param {Object} propertyValues
                }
    * @returns {mw.calculators.objectClasses.CalculatorObject}
    * @constructor
    */
    mw.calculators.objectClasses.CalculatorObject = function( properties, propertyValues ) {
        propertyValues = propertyValues ? propertyValues : {};


        if( properties ) {
                $( this ).append( $descriptionContainer );
            if( properties.hasOwnProperty( 'required' ) ) {
                for( var iRequiredProperty in properties.required ) {
                    var requiredProperty = properties.required[ iRequiredProperty ];


                    if( !propertyValues || !propertyValues.hasOwnProperty( requiredProperty ) ) {
                descriptionCount++;
                        console.error( 'Missing required property "' + requiredProperty + '"' );
            } );
                        console.log( propertyValues );


                        return null;
            // Set options
                    }
            mw.calculators.setDefaultOptions();


                    this[ requiredProperty ] = propertyValues[ requiredProperty ];
            var $optionsElement = $( mw.calculators.selectors.calculatorOptions );
 
            if( $optionsElement.length ) {
                     delete propertyValues[ requiredProperty ];
                $.each( $optionsElement.data(), function( optionId, value ) {
                 }
                     mw.calculators.setOptionValue( optionId, value );
                 } );
             }
             }


             if( properties.hasOwnProperty( 'optional' ) ) {
             mw.hook( 'calculators.initialized' ).fire();
                for( var iOptionalProperty in properties.optional ) {
        },
                    var optionalProperty = properties.optional[ iOptionalProperty ];
        isMobile: function() {
            return window.matchMedia( 'only screen and (max-width: 760px)' ).matches;
        },
        isValueMathObject: function( value ) {
            return value && value.hasOwnProperty( 'value' );
        },
        prepareReferences: function( references ) {
            for( var iReference in references ) {
                var reference = references[ iReference ];
 
                // http(s)
                reference = reference.replace(
                    /(https?:\/\/[^\s]*)/gmi,
                    '<a href="$1" target="_blank">$1</a>'
                );


                     if( propertyValues && propertyValues.hasOwnProperty( optionalProperty ) ) {
                // doi
                        this[ optionalProperty ] = propertyValues[ optionalProperty ];
                reference = reference.replace(
                     /doi: ([\w\d\.\/-]+)((\.\s)|$)/gmi,
                    'doi: <a href="https://doi.org/$1" target="_blank">$1</a>$2'
                );


                        delete propertyValues[ optionalProperty ];
                // PMCID
                     } else if( typeof this[ optionalProperty ] === 'undefined' ) {
                reference = reference.replace(
                        this[ optionalProperty ] = null;
                     /PMCID: PMC(\d+)/gmi,
                    }
                    'PMCID: <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC$1/" target="_blank">PMC$1</a>'
                }
                );
            }


            var invalidProperties = Object.keys( propertyValues );
                // PMID
                reference = reference.replace(
                    /PMID: (\d+)/gmi,
                    'PMID: <a href="https://pubmed.ncbi.nlm.nih.gov/$1" target="_blank">$1</a>'
                );


            if( invalidProperties.length ) {
                 references[ iReference ] = reference;
                 console.warn( 'Unsupported properties defined for ' + typeof this + ' with id "' + this.id + '": ' + invalidProperties.join( ', ' ) );
             }
             }
        }
    };


    mw.calculators.objectClasses.CalculatorObject.prototype.getProperties = function() {
            return references;
         return {
        },
             required: [],
        setCookieValue: function( variableId, value ) {
             optional: []
            mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
        };
                expires: COOKIE_EXPIRATION
    };
            } );
        },
         setDefaultOptions: function() {
             mw.calculators.setOptionValue( 'inputgroupmaxinputsperrow', 3 );
        },
        setOptionValue: function( optionId, value ) {
             mw.calculators.options[ optionId ] = value;


    mw.calculators.objectClasses.CalculatorObject.prototype.mergeProperties = function( inheritedProperties, properties ) {
            return true;
         var uniqueValues = function( value, index, self ) {
        },
             return self.indexOf( value ) === index;
         setValue: function( variableId, value ) {
        };
             if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return false;
            }


        properties.required = inheritedProperties.required.concat( properties.required ).filter( uniqueValues );
            if( !mw.calculators.variables[ variableId ].setValue( value ) ) {
        properties.optional = inheritedProperties.optional.concat( properties.optional ).filter( uniqueValues );
                return false;
            }
 
            mw.calculators.setCookieValue( variableId, value );


         return properties;
            return true;
        },
         uniqueValues: function( value, index, self ) {
            return self.indexOf( value ) === index;
        }
     };
     };


     /**
     /**
     * Class UnitsBase
     * Class CalculatorObject
    *
    * @param {Object} properties
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.UnitsBase}
     * @returns {mw.calculators.objectClasses.CalculatorObject}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.UnitsBase = function( propertyValues ) {
     mw.calculators.objectClasses.CalculatorObject = function( properties, propertyValues ) {
         var properties = {
         propertyValues = propertyValues ? propertyValues : {};
             required: [
 
                 'id'
        if( properties ) {
            ],
             if( properties.hasOwnProperty( 'required' ) ) {
            optional: [
                 for( var iRequiredProperty in properties.required ) {
                'toString'
                    var requiredProperty = properties.required[ iRequiredProperty ];
            ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
                    if( !propertyValues || !propertyValues.hasOwnProperty( requiredProperty ) ) {
    };
                        console.error( 'Missing required property "' + requiredProperty + '"' );
                        console.log( propertyValues );


    mw.calculators.objectClasses.UnitsBase.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                        return null;
                    }


                    this[ requiredProperty ] = propertyValues[ requiredProperty ];


                    delete propertyValues[ requiredProperty ];
                }
            }


            if( properties.hasOwnProperty( 'optional' ) ) {
                for( var iOptionalProperty in properties.optional ) {
                    var optionalProperty = properties.optional[ iOptionalProperty ];


    /**
                    if( propertyValues && propertyValues.hasOwnProperty( optionalProperty ) ) {
    * Class Units
                        this[ optionalProperty ] = propertyValues[ optionalProperty ];
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.Units}
    * @constructor
    */
    mw.calculators.objectClasses.Units = function( propertyValues ) {
        var properties = {
            required: [
                'id'
            ],
            optional: [
                'aliases',
                'baseName',
                'definition',
                'offset',
                'prefixes'
            ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
                        delete propertyValues[ optionalProperty ];
    };
                    } else if( typeof this[ optionalProperty ] === 'undefined' ) {
                        this[ optionalProperty ] = null;
                    }
                }
            }


     mw.calculators.objectClasses.Units.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
            var invalidProperties = Object.keys( propertyValues );
 
            if( invalidProperties.length ) {
                console.warn( 'Unsupported properties defined for ' + typeof this + ' with id "' + this.id + '": ' + invalidProperties.join( ', ' ) );
            }
        }
    };
 
     mw.calculators.objectClasses.CalculatorObject.prototype.getProperties = function() {
        return {
            required: [],
            optional: []
        };
    };
 
    mw.calculators.objectClasses.CalculatorObject.prototype.mergeProperties = function( inheritedProperties, properties ) {
        var uniqueValues = function( value, index, self ) {
            return self.indexOf( value ) === index;
        };
 
        properties.required = inheritedProperties.required.concat( properties.required ).filter( uniqueValues );
        properties.optional = inheritedProperties.optional.concat( properties.optional ).filter( uniqueValues );
 
        return properties;
    };




Line 533: Line 599:


     /**
     /**
     * Class Variable
     * Class UnitsBase
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.Variable}
     * @returns {mw.calculators.objectClasses.UnitsBase}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.Variable = function( propertyValues ) {
     mw.calculators.objectClasses.UnitsBase = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
         var properties = {
            required: [
                'id'
            ],
            optional: [
                'toString'
            ]
        };


         if( VALID_TYPES.indexOf( this.type ) === -1 ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
            throw new Error( 'Invalid type "' + this.type + '" for variable "' + this.id + '"' );
    };
        }


        // Accept options as either an array of strings, or an object with ids as keys and display text as values
    mw.calculators.objectClasses.UnitsBase.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        if( Array.isArray( this.options ) ) {
            var options = {};


            for( var iOption in this.options ) {
                var option = this.options[ iOption ];


                options[ option ] = option;
            }


            this.options = options;
        }


         this.calculations = [];
    /**
    * Class Units
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.Units}
    * @constructor
    */
    mw.calculators.objectClasses.Units = function( propertyValues ) {
         var properties = {
            required: [
                'id'
            ],
            optional: [
                'aliases',
                'baseName',
                'definition',
                'formatValue',
                'offset',
                'prefixes'
            ]
        };
 
        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
    };


        if( this.defaultValue ) {
    mw.calculators.objectClasses.Units.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
            this.defaultValue = this.prepareValue( this.defaultValue );
        }


        if( this.minValue ) {
            this.minValue = this.prepareValue( this.minValue );
        }


        if( this.maxValue ) {
            this.maxValue = this.prepareValue( this.maxValue );
        }


        this.message = null;
        this.valid = true;


        this.isValueSet = false;
    /**
         this.value = null;
    * Class Variable
    };
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.Variable}
    * @constructor
    */
    mw.calculators.objectClasses.Variable = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


    mw.calculators.objectClasses.Variable.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
         if( VALID_TYPES.indexOf( this.type ) === -1 ) {
 
             throw new Error( 'Invalid type "' + this.type + '" for variable "' + this.id + '"' );
    mw.calculators.objectClasses.Variable.prototype.addCalculation = function( calculationId ) {
         if( this.calculations.indexOf( calculationId ) !== -1 ) {
             return;
         }
         }


         this.calculations.push( calculationId );
         // Accept options as either an array of strings, or an object with ids as keys and display text as values
    };
        if( Array.isArray( this.options ) ) {
            var options = {};


    mw.calculators.objectClasses.Variable.prototype.createInput = function( inputOptions ) {
            for( var iOption in this.options ) {
        if( !inputOptions ) {
                var option = this.options[ iOption ];
            inputOptions = {};
        }


        inputOptions.class = inputOptions.hasOwnProperty( 'class' ) ? inputOptions.class : '';
                options[ option ] = option;
        inputOptions.global = inputOptions.hasOwnProperty( 'class' ) ? inputOptions.global : false;
        inputOptions.hideLabel = inputOptions.hasOwnProperty( 'hideLabel' ) ? inputOptions.hideLabel : false;
        inputOptions.hideLabelMobile = inputOptions.hasOwnProperty( 'hideLabelMobile' ) ? inputOptions.hideLabelMobile : false;
        inputOptions.inline = inputOptions.hasOwnProperty( 'inline' ) ? inputOptions.inline : false;
        inputOptions.inputClass = inputOptions.hasOwnProperty( 'inputClass' ) ? inputOptions.inputClass : '';
 
        var variableId = this.id;
        var inputId = 'calculator-input-' + variableId;
 
        // If not creating a global input, assign an iterated id
        if( !inputOptions.global ) {
            var inputIdCount = 0;
 
            while( $( '#' + inputId + '-' + inputIdCount ).length ) {
                inputIdCount++;
             }
             }


             inputId += '-' + inputIdCount;
             this.options = options;
         }
         }


         var inputContainerTag = inputOptions.inline ? '<span>' : '<div>';
         this.calculations = [];


         var inputContainerAttributes = {
         if( this.defaultValue ) {
             class: 'form-group mb-0 calculator-container-input'
             this.defaultValue = this.prepareValue( this.defaultValue );
         };
         }


         inputContainerAttributes.class += inputOptions.class ? ' ' + inputOptions.class : '';
         if( this.minValue ) {
         inputContainerAttributes.class += ' calculator-container-input-' + variableId;
            this.minValue = this.prepareValue( this.minValue );
         }


         var inputContainerCss = {};
         if( this.maxValue ) {
 
             this.maxValue = this.prepareValue( this.maxValue );
        // Initialize label attributes
        var labelAttributes = {
            for: inputId,
             html: this.getLabelString()
        };
 
        if( inputOptions.hideLabel || ( inputOptions.hideLabelMobile && mw.calculators.isMobile() ) ) {
            labelAttributes.class = 'sr-only';
         }
         }


         var labelCss = {};
         this.message = null;
        this.valid = true;


         if( inputOptions.inline ) {
         this.isValueSet = false;
            inputContainerTag = '<span>';
        this.value = null;
    };


            inputContainerCss[ 'align-items' ] = 'center';
    mw.calculators.objectClasses.Variable.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
            inputContainerCss[ 'display' ] = 'flex';
            //inputContainerCss[ 'height' ] = 'calc(1.5em + 0.75rem + 2px)';


            labelAttributes.html += ':&nbsp;';
    mw.calculators.objectClasses.Variable.prototype.addCalculation = function( calculationId ) {
             labelCss[ 'margin-bottom' ] = 0;
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
             return;
         }
         }


         // Create the input container
         this.calculations.push( calculationId );
        var $inputContainer = $( inputContainerTag, inputContainerAttributes ).css( inputContainerCss );
    };


        var $label = $( '<label>', labelAttributes ).css( labelCss );
    mw.calculators.objectClasses.Variable.prototype.createInput = function( inputOptions ) {
        if( !inputOptions ) {
            inputOptions = {};
        }


         $inputContainer.append( $label );
         inputOptions.class = inputOptions.hasOwnProperty( 'class' ) ? inputOptions.class : '';
        inputOptions.global = inputOptions.hasOwnProperty( 'class' ) ? inputOptions.global : false;
        inputOptions.hideLabel = inputOptions.hasOwnProperty( 'hideLabel' ) ? inputOptions.hideLabel : false;
        inputOptions.hideLabelMobile = inputOptions.hasOwnProperty( 'hideLabelMobile' ) ? inputOptions.hideLabelMobile : false;
        inputOptions.inline = inputOptions.hasOwnProperty( 'inline' ) ? inputOptions.inline : false;
        inputOptions.inputClass = inputOptions.hasOwnProperty( 'inputClass' ) ? inputOptions.inputClass : '';


        // 'this' will be redefined for event handlers
         var variableId = this.id;
         var variable = this;
         var inputId = 'calculator-input-' + variableId;
         var value = this.getValue();


         if( this.type === TYPE_NUMBER ) {
        // If not creating a global input, assign an iterated id
            // Initialize the primary units variables (needed for handlers, even if doesn't have units)
         if( !inputOptions.global ) {
            var unitsId = null;
             var inputIdCount = 0;
             var $unitsContainer = null;


             var inputValue = '';
             while( $( '#' + inputId + '-' + inputIdCount ).length ) {
                inputIdCount++;
            }


             if( mw.calculators.isValueMathObject( value ) ) {
             inputId += '-' + inputIdCount;
                var number = value.toNumber();
        }


                if( number ) {
        var inputContainerTag = inputOptions.inline ? '<span>' : '<div>';
                    inputValue = number;
                }
            } else {
                inputValue = value;
            }


            // Initialize input options
        var inputContainerAttributes = {
            var inputAttributes = {
            class: 'form-group mb-0 calculator-container-input'
                id: inputId,
        };
                class: 'form-control form-control-sm calculator-input calculator-input-text',
                type: 'text',
                autocomplete: 'off',
                inputmode: 'decimal',
                value: inputValue
            };


            // Configure additional options
        inputContainerAttributes.class += inputOptions.class ? ' ' + inputOptions.class : '';
            if( this.maxLength ) {
        inputContainerAttributes.class += ' calculator-container-input-' + variableId;
                inputAttributes.maxlength = this.maxLength;
            }


            // Add any additional classes to the input
        var inputContainerCss = {};
            inputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';


            // Add the input id to the list of classes
        // Initialize label attributes
             inputAttributes.class += ' ' + inputId;
        var labelAttributes = {
             for: inputId,
            html: this.getLabelString()
        };


            // If the variable has units, create the units input
        if( inputOptions.hideLabel || ( inputOptions.hideLabelMobile && mw.calculators.isMobile() ) ) {
            if( this.hasUnits() ) {
            labelAttributes.class = 'sr-only';
                // Set the units id
        }
                unitsId = inputId + '-units';


                var unitsValue = mw.calculators.isValueMathObject( value ) ? value.formatUnits() : null;
        var labelCss = {};


                var unitsInputAttributes = {
        if( inputOptions.inline ) {
                    id: unitsId
            inputContainerTag = '<span>';
                };


                // Create the units container
            inputContainerCss[ 'align-items' ] = 'center';
                $unitsContainer = $( '<div>', {
            inputContainerCss[ 'display' ] = 'flex';
                    class: 'input-group-append'
            //inputContainerCss[ 'height' ] = 'calc(1.5em + 0.75rem + 2px)';
                } ).css( 'align-items', 'center' );


                if( this.units.length === 1 ) {
            labelAttributes.html += ':&nbsp;';
                    unitsInputAttributes.type = 'hidden';
            labelCss[ 'margin-bottom' ] = 0;
                    unitsInputAttributes.value = this.units[ 0 ];
        }


                    $unitsContainer
        // Create the input container
                        .css( 'padding', '0 0.5em' )
        var $inputContainer = $( inputContainerTag, inputContainerAttributes ).css( inputContainerCss );
                        .append( mw.calculators.getUnitsString( math.unit( '0 ' + this.units[ 0 ] ) ) )
                        .append( $( '<input>', unitsInputAttributes ) );
                } else {
                    // Initialize the units input options
                    unitsInputAttributes.class = 'custom-select custom-select-sm calculator-input-select';


                    // Add any additional classes to the input
        var $label = $( '<label>', labelAttributes ).css( labelCss );
                    unitsInputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';


                    unitsInputAttributes.class = unitsInputAttributes.class + ' ' + unitsId;
        $inputContainer.append( $label );


                    var $unitsInput = $( '<select>', unitsInputAttributes )
        // 'this' will be redefined for event handlers
                        .on( 'change', function() {
        var variable = this;
                            var numberValue = $( '#' + inputId ).val();
        var value = this.getValue();


                            var newValue = numberValue ? numberValue + ' ' + $( this ).val() : null;
        if( this.type === TYPE_NUMBER ) {
            // Initialize the primary units variables (needed for handlers, even if doesn't have units)
            var unitsId = null;
            var $unitsContainer = null;


                            if( !mw.calculators.setValue( variableId, newValue ) ) {
            var inputValue = '';
                                if( variable.message ) {
                                    $( this ).parent().parent().parent().find( '.invalid-feedback' ).html( variable.message );
                                }


                                $( this ).parent().parent().addClass( 'is-invalid' );
            if( mw.calculators.isValueMathObject( value ) ) {
                            } else {
                var number = value.toNumber();
                                $( this ).parent().parent().removeClass( 'is-invalid' );
                            }
                        } );


                    for( var iUnits in this.units ) {
                if( number ) {
                        var units = this.units[ iUnits ];
                    inputValue = number;
 
                        var unitsOptionAttributes = {
                            html: mw.calculators.getUnitsString( math.unit( '0 ' + units ) ),
                            value: units
                        };
 
                        if( units === unitsValue ) {
                            unitsOptionAttributes.selected = true;
                        }
 
                        $unitsInput.append( $( '<option>', unitsOptionAttributes ) );
                    }
 
                    $unitsContainer.append( $unitsInput );
                 }
                 }
            } else {
                inputValue = value;
             }
             }


             // Create the input and add handlers
             // Initialize input options
             var $input = $( '<input>', inputAttributes )
             var inputAttributes = {
                 .on( 'input', function() {
                id: inputId,
                    var numberValue = $( this ).val();
                class: 'form-control form-control-sm calculator-input calculator-input-text',
                type: 'text',
                autocomplete: 'off',
                 inputmode: 'decimal',
                value: inputValue
            };


                    var newValue = numberValue ? numberValue : null;
            // Configure additional options
            if( this.maxLength ) {
                inputAttributes.maxlength = this.maxLength;
            }


                    if( newValue && unitsId ) {
            // Add any additional classes to the input
                        newValue = newValue + ' ' + $( '#' + unitsId ).val();
            inputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
                    }


                    if( !mw.calculators.setValue( variableId, newValue ) ) {
            // Add the input id to the list of classes
                        if( variable.message ) {
            inputAttributes.class += ' ' + inputId;
                            $( this ).parent().parent().find( '.invalid-feedback' ).html( variable.message );
                        }


                        $( this ).parent().addClass( 'is-invalid' );
            // If the variable has units, create the units input
                    } else {
            if( this.hasUnits() ) {
                        $( this ).parent().removeClass( 'is-invalid' );
                // Set the units id
                    }
                unitsId = inputId + '-units';
                } );


            // Create the input group
                var unitsValue = mw.calculators.isValueMathObject( value ) ? value.formatUnits() : null;
            var $inputGroup = $( '<div>', {
                class: 'input-group'
            } ).append( $input );


            if( $unitsContainer ) {
                var unitsInputAttributes = {
                 $inputGroup.append( $unitsContainer );
                    id: unitsId
            }
                 };


            $inputContainer.append( $inputGroup );
                // Create the units container
        } else if( this.type === TYPE_STRING ) {
                $unitsContainer = $( '<div>', {
            if( this.hasOptions() ) {
                    class: 'input-group-append'
                 var optionKeys = Object.keys( this.options );
                 } ).css( 'align-items', 'center' );


                 if( optionKeys.length === 1 ) {
                 if( this.units.length === 1 ) {
                     $inputContainer.append( this.options[ optionKeys[ 0 ] ] );
                    unitsInputAttributes.type = 'hidden';
                    unitsInputAttributes.value = this.units[ 0 ];
 
                     $unitsContainer
                        .css( 'padding', '0 0.5em' )
                        .append( mw.calculators.getUnitsString( math.unit( '0 ' + this.units[ 0 ] ) ) )
                        .append( $( '<input>', unitsInputAttributes ) );
                 } else {
                 } else {
                     var selectAttributes = {
                     // Initialize the units input options
                        id: inputId,
                    unitsInputAttributes.class = 'custom-select custom-select-sm calculator-input-select';
                        class: 'custom-select custom-select-sm calculator-input calculator-input-select'
                    };


                     // Add any additional classes to the input
                     // Add any additional classes to the input
                     selectAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
                     unitsInputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
 
                    unitsInputAttributes.class = unitsInputAttributes.class + ' ' + unitsId;


                     var $select = $( '<select>', selectAttributes )
                     var $unitsInput = $( '<select>', unitsInputAttributes )
                         .on( 'change', function() {
                         .on( 'change', function() {
                             if( !mw.calculators.setValue( variableId, $( this ).val() ) ) {
                             var numberValue = $( '#' + inputId ).val();
                                if( variable.message ) {
 
                                    $( this ).parent().parent().find( '.invalid-feedback' ).html( variable.message );
                            var newValue = numberValue ? numberValue + ' ' + $( this ).val() : null;
                                }


                                 $( this ).parent().addClass( 'is-invalid' );
                            if( !mw.calculators.setValue( variableId, newValue ) ) {
                                if( variable.message ) {
                                    $( this ).parent().parent().parent().find( '.invalid-feedback' ).html( variable.message );
                                }
 
                                 $( this ).parent().parent().addClass( 'is-invalid' );
                             } else {
                             } else {
                                 $( this ).parent().removeClass( 'is-invalid' );
                                 $( this ).parent().parent().removeClass( 'is-invalid' );
                             }
                             }
                         } );
                         } );


                     for( var optionId in this.options ) {
                     for( var iUnits in this.units ) {
                         var displayText = this.options[ optionId ];
                         var units = this.units[ iUnits ];


                         var optionAttributes = {
                         var unitsOptionAttributes = {
                             value: optionId,
                             html: mw.calculators.getUnitsString( math.unit( '0 ' + units ) ),
                             text: displayText
                             value: units
                         };
                         };


                         if( optionId == value ) {
                         if( units === unitsValue ) {
                             optionAttributes.selected = true;
                             unitsOptionAttributes.selected = true;
                         }
                         }


                         $select.append( $( '<option>', optionAttributes ) );
                         $unitsInput.append( $( '<option>', unitsOptionAttributes ) );
                     }
                     }


                     $inputContainer.append( $select );
                     $unitsContainer.append( $unitsInput );
                 }
                 }
             }
             }
        }


        if( $inputContainer.length ) {
            // Create the input and add handlers
             $inputContainer.append( $( '<div>', {
             var $input = $( '<input>', inputAttributes )
                 class: 'invalid-feedback'
                 .on( 'input', function() {
            } ) );
                    var numberValue = $( this ).val();
        }
 
                    var newValue = numberValue ? numberValue : null;


        return $inputContainer;
                    if( newValue && unitsId ) {
    };
                        newValue = newValue + ' ' + $( '#' + unitsId ).val();
                    }


    mw.calculators.objectClasses.Variable.prototype.getLabelString = function() {
                    if( !mw.calculators.setValue( variableId, newValue ) ) {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
                        if( variable.message ) {
    };
                            $( this ).parent().parent().find( '.invalid-feedback' ).html( variable.message );
                        }


    mw.calculators.objectClasses.Variable.prototype.getProperties = function() {
                        $( this ).parent().addClass( 'is-invalid' );
        return {
                    } else {
            required: [
                        $( this ).parent().removeClass( 'is-invalid' );
                'id',
                    }
                 'name',
                 } );
                'type'
 
             ],
             // Create the input group
             optional: [
             var $inputGroup = $( '<div>', {
                'abbreviation',
                 class: 'input-group'
                'defaultValue',
             } ).append( $input );
                'maxLength',
                 'maxValue',
                'minValue',
                'options',
                'units'
             ]
        };
    };


    mw.calculators.objectClasses.Variable.prototype.getValue = function() {
             if( $unitsContainer ) {
        if( !this.valid ) {
                $inputGroup.append( $unitsContainer );
             return null;
             }
        } else if( this.value !== null ) {
            return this.value;
        } else if( !this.isValueSet && this.defaultValue !== null ) {
            return this.defaultValue;
        } else {
             return null;
        }
    };


    mw.calculators.objectClasses.Variable.prototype.getValueString = function() {
            $inputContainer.append( $inputGroup );
        return String( this.getValue() );
        } else if( this.type === TYPE_STRING ) {
    };
            if( this.hasOptions() ) {
                var optionKeys = Object.keys( this.options );


    mw.calculators.objectClasses.Variable.prototype.hasOptions = function() {
                if( optionKeys.length === 1 ) {
        return this.options !== null;
                    $inputContainer.append( this.options[ optionKeys[ 0 ] ] );
    };
                } else {
                    var selectAttributes = {
                        id: inputId,
                        class: 'custom-select custom-select-sm calculator-input calculator-input-select'
                    };


    mw.calculators.objectClasses.Variable.prototype.hasUnits = function() {
                    // Add any additional classes to the input
        return this.units !== null;
                    selectAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
    };


    mw.calculators.objectClasses.Variable.prototype.hasValue = function() {
                    var $select = $( '<select>', selectAttributes )
        var value = this.getValue();
                        .on( 'change', function() {
                            if( !mw.calculators.setValue( variableId, $( this ).val() ) ) {
                                if( variable.message ) {
                                    $( this ).parent().parent().find( '.invalid-feedback' ).html( variable.message );
                                }


        if( value === null ||
                                $( this ).parent().addClass( 'is-invalid' );
            ( mw.calculators.isValueMathObject( value ) && !value.toNumber() ) ) {
                            } else {
            return false;
                                $( this ).parent().removeClass( 'is-invalid' );
        }
                            }


        return true;
                        } );
    };


    mw.calculators.objectClasses.Variable.prototype.isValueMathObject = function() {
                    for( var optionId in this.options ) {
        return mw.calculators.isValueMathObject( this.value );
                        var displayText = this.options[ optionId ];
    };


    mw.calculators.objectClasses.Variable.prototype.prepareValue = function( value ) {
                        var optionAttributes = {
        if( value !== null ) {
                            value: optionId,
            if( this.type === TYPE_NUMBER ) {
                            text: displayText
                if( !mw.calculators.isValueMathObject( value ) ) {
                        };
                     value = math.unit( value );
 
                        if( optionId == value ) {
                            optionAttributes.selected = true;
                        }
 
                        $select.append( $( '<option>', optionAttributes ) );
                    }
 
                     $inputContainer.append( $select );
                 }
                 }
             }
             }
         }
         }


         return value;
        if( $inputContainer.length ) {
            $inputContainer.append( $( '<div>', {
                class: 'invalid-feedback'
            } ) );
        }
 
         return $inputContainer;
     };
     };


     mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
     mw.calculators.objectClasses.Variable.prototype.getLabelString = function() {
         // Set flag to prevent returning defaultValue in getValue()
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
        this.isValueSet = true;
    };


        var validateResult = this.validateValue( value );
    mw.calculators.objectClasses.Variable.prototype.getProperties = function() {
 
        return {
         this.valid = !!validateResult.valid;
            required: [
        this.message = validateResult.message;
                'id',
                'name',
                'type'
            ],
            optional: [
                'abbreviation',
                'defaultValue',
                'maxLength',
                'maxValue',
                'minValue',
                'options',
                'units'
            ]
         };
    };


    mw.calculators.objectClasses.Variable.prototype.getValue = function() {
         if( !this.valid ) {
         if( !this.valid ) {
             this.value = null;
             return null;
             this.valueUpdated();
        } else if( this.value !== null ) {
 
             return this.value;
             return false;
        } else if( !this.isValueSet && this.defaultValue !== null ) {
            return this.defaultValue;
        } else {
             return null;
         }
         }
    };


        this.value = this.prepareValue( value );
    mw.calculators.objectClasses.Variable.prototype.getValueString = function() {
        return String( this.getValue() );
    };


        this.valueUpdated();
    mw.calculators.objectClasses.Variable.prototype.hasOptions = function() {
 
         return this.options !== null;
         return true;
     };
     };


     mw.calculators.objectClasses.Variable.prototype.toString = function() {
     mw.calculators.objectClasses.Variable.prototype.hasUnits = function() {
         return this.getLabelString();
         return this.units !== null;
     };
     };


     mw.calculators.objectClasses.Variable.prototype.validateValue = function( value ) {
     mw.calculators.objectClasses.Variable.prototype.hasValue = function() {
         // Initialize valid flag to true. Will be set false if an error is found.
         var value = this.getValue();
        result = {
            message: null,
            valid: true
        };


        // (At least for now) unsetting a variable is always valid
         if( value === null ||
         if( value === null ) {
            ( mw.calculators.isValueMathObject( value ) && !value.toNumber() ) ) {
            return result;
            return false;
         }
         }


         // Some errors which are plausibly from normal user input we will show as feedback on the input (e.g.
         return true;
        // a numeric value that is below the minimum value. Errors which are unlikely to be from user input
    };
        // and instead relate to developer issues (e.g. incorrect units in select boxes), only show on the console.
        var consoleWarnPrefix = 'Could not set value "' + value + '" for "' + this.id + '":';


        if( this.type === TYPE_NUMBER ) {
    mw.calculators.objectClasses.Variable.prototype.isValueMathObject = function() {
            if( !mw.calculators.isValueMathObject( value ) ) {
        return mw.calculators.isValueMathObject( this.value );
                value = math.unit( value );
    };
            }


            var valueUnits;
    mw.calculators.objectClasses.Variable.prototype.prepareValue = function( value ) {
 
        if( value !== null ) {
            if( this.hasUnits() ) {
            if( this.type === TYPE_NUMBER ) {
                valueUnits = value.formatUnits();
                 if( !mw.calculators.isValueMathObject( value ) ) {
 
                     value = math.unit( value );
                if( !valueUnits ) {
                    // Unlikely to be a user error, so don't set message.
                    result.valid = false;
 
                    console.warn( consoleWarnPrefix + 'Value must define units' );
                 } else if( this.units.indexOf( valueUnits ) === -1 ) {
                     // Unlikely to be a user error, so don't set message.
                    result.valid = false;
 
                    console.warn( consoleWarnPrefix + 'Units "' + valueUnits + '" are not valid for this variable' );
                 }
                 }
             }
             }
        }
        return value;
    };


            if( this.minValue && math.smaller( value, this.minValue ) ) {
    mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
                var minValueString = mw.calculators.getValueString( this.minValue );
        // Set flag to prevent returning defaultValue in getValue()
        this.isValueSet = true;


                if( valueUnits && valueUnits != this.minValue.formatUnits() ) {
        var validateResult = this.validateValue( value );
                    minValueString += ' (' + mw.calculators.getValueString( this.minValue.to( valueUnits ) ) + ')';
                }


                result.message = String( this ) + ' must be at least ' + minValueString;
        this.valid = !!validateResult.valid;
                result.valid = false;
        this.message = validateResult.message;
            } else if( this.maxValue && math.larger( value, this.maxValue ) ) {
 
                var maxValueString = mw.calculators.getValueString( this.maxValue );
        if( !this.valid ) {
            this.value = null;
            this.valueUpdated();


                if( valueUnits && valueUnits != this.maxValue.formatUnits() ) {
            return false;
                    maxValueString += ' (' + mw.calculators.getValueString( this.maxValue.to( valueUnits ) ) + ')';
        }
                }


                result.message = String( this ) + ' must be less than ' + maxValueString;
        this.value = this.prepareValue( value );
                result.valid = false;
            }
        } else if( this.hasOptions() ) {
            if( !this.options.hasOwnProperty( value ) ) {
                // Unlikely to be a user error, so don't set message
                result.valid = false;


                console.warn( consoleWarnPrefix + 'Value must be one of: ' + Object.keys( this.options ).join( ', ' ) );
        this.valueUpdated();
            }
        }


         return result;
         return true;
     };
     };


     mw.calculators.objectClasses.Variable.prototype.valueUpdated = function() {
     mw.calculators.objectClasses.Variable.prototype.toString = function() {
         for( var iCalculation in this.calculations ) {
         return this.getLabelString();
            var calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );
    };
 
    mw.calculators.objectClasses.Variable.prototype.validateValue = function( value ) {
        // Initialize valid flag to true. Will be set false if an error is found.
        result = {
            message: null,
            valid: true
        };


            if( calculation ) {
        // (At least for now) unsetting a variable is always valid
                calculation.render();
        if( value === null ) {
            }
            return result;
         }
         }
    };


        // Some errors which are plausibly from normal user input we will show as feedback on the input (e.g.
        // a numeric value that is below the minimum value. Errors which are unlikely to be from user input
        // and instead relate to developer issues (e.g. incorrect units in select boxes), only show on the console.
        var consoleWarnPrefix = 'Could not set value "' + value + '" for "' + this.id + '":';


        if( this.type === TYPE_NUMBER ) {
            if( !mw.calculators.isValueMathObject( value ) ) {
                value = math.unit( value );
            }


    /**
            var valueUnits;
    * Class AbstractCalculation
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.AbstractCalculation}
    * @constructor
    */
    mw.calculators.objectClasses.AbstractCalculation = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


        this.initialize();
            if( this.hasUnits() ) {
    };
                valueUnits = value.formatUnits().replace( /\s/g, '' );


    mw.calculators.objectClasses.AbstractCalculation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                if( !valueUnits ) {
                    // Unlikely to be a user error, so don't set message.
                    result.valid = false;


    mw.calculators.objectClasses.AbstractCalculation.prototype.addCalculation = function( calculationId ) {
                    console.warn( consoleWarnPrefix + 'Value must define units' );
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
                } else if( this.units.indexOf( valueUnits ) === -1 ) {
            return;
                    // Unlikely to be a user error, so don't set message.
        }
                    result.valid = false;


        this.calculations.push( calculationId );
                    console.warn( consoleWarnPrefix + 'Units "' + valueUnits + '" are not valid for this variable' );
    };
                }
            }


    mw.calculators.objectClasses.AbstractCalculation.prototype.doRender = function() {
            if( this.minValue && math.smaller( value, this.minValue ) ) {
        throw new Error( 'AbstractCalculation child class "' + this.getClassName() + '" must implement doRender()' );
                var minValueString = mw.calculators.getValueString( this.minValue );
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationData = function() {
                if( valueUnits && valueUnits != this.minValue.formatUnits() ) {
        return this.data;
                    minValueString += ' (' + mw.calculators.getValueString( this.minValue.to( valueUnits ) ) + ')';
    };
                }


    mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationDataValues = function() {
                result.message = String( this ) + ' must be at least ' + minValueString;
        var calculationData = this.getCalculationData();
                result.valid = false;
            } else if( this.maxValue && math.larger( value, this.maxValue ) ) {
                var maxValueString = mw.calculators.getValueString( this.maxValue );


        var missingRequiredData = this.getMissingRequiredData();
                if( valueUnits && valueUnits != this.maxValue.formatUnits() ) {
                    maxValueString += ' (' + mw.calculators.getValueString( this.maxValue.to( valueUnits ) ) + ')';
                }


         if( missingRequiredData.length ) {
                result.message = String( this ) + ' must be less than ' + maxValueString;
             this.message = missingRequiredData.join( ', ' ) + ' required';
                result.valid = false;
 
            }
             return false;
         } else if( this.hasOptions() ) {
             if( !this.options.hasOwnProperty( value ) ) {
                // Unlikely to be a user error, so don't set message
                result.valid = false;
 
                console.warn( consoleWarnPrefix + 'Value must be one of: ' + Object.keys( this.options ).join( ', ' ) );
             }
         }
         }


         var data = {};
         return result;
    };


         var calculationId, calculation, variableId, variable;
    mw.calculators.objectClasses.Variable.prototype.valueUpdated = function() {
         for( var iCalculation in this.calculations ) {
            var calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );


        var calculations = calculationData.calculations.required.concat( calculationData.calculations.optional );
            if( calculation ) {
 
                calculation.update();
         for( var iRequiredCalculation in calculations ) {
            }
            calculationId = calculations[ iRequiredCalculation ];
         }
            calculation = mw.calculators.getCalculation( calculationId );
    };


            // We shouldn't use getValue() since that triggers recalculate() which would cause an infinite loop
            data[ calculationId ] = calculation.value;
        }


        var variables = calculationData.variables.required.concat( calculationData.variables.optional );


         for( var iRequiredVariable in variables ) {
    /**
            variableId = variables[ iRequiredVariable ];
    * Class AbstractCalculation
            variable = mw.calculators.getVariable( variableId );
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.AbstractCalculation}
    * @constructor
    */
    mw.calculators.objectClasses.AbstractCalculation = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
 
         this.initialize();
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );


            data[ variableId ] = variable.getValue();
    mw.calculators.objectClasses.AbstractCalculation.prototype.addCalculation = function( calculationId ) {
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
            return;
         }
         }


         return data;
         this.calculations.push( calculationId );
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.getClassName = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.doRender = function() {
         throw new Error( 'AbstractCalculation child class must implement getClassName()' );
         throw new Error( 'AbstractCalculation child class "' + this.getClassName() + '" must implement doRender()' );
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerClasses = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationData = function() {
         return this.getElementClasses();
         return this.data;
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerId = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationDataValues = function() {
         return this.getElementPrefix() + '-' + this.id;
         var calculationData = this.getCalculationData();
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getDescription = function() {
        var missingRequiredData = this.getMissingRequiredData();
        return this.description;
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getElementPrefix = function( useClassName ) {
        if( missingRequiredData.length ) {
        var elementPrefix = 'calculator-';
            this.message = missingRequiredData.join( ', ' ) + ' required';


         elementPrefix += useClassName ? this.getClassName() : 'calculation';
            return false;
         }


         return elementPrefix;
         var data = {};
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getElementClasses = function( elementId ) {
         var calculationId, calculation, variableId, variable;
         elementId = elementId ? '-' + elementId : '';


         return this.getElementPrefix() + elementId + ' ' +
         var calculations = calculationData.calculations.required.concat( calculationData.calculations.optional );
            this.getElementPrefix( true ) + elementId + ' ' +
            this.getContainerId() + elementId;
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getFormula = function() {
        for( var iRequiredCalculation in calculations ) {
        return this.formula;
            calculationId = calculations[ iRequiredCalculation ];
    };
            calculation = mw.calculators.getCalculation( calculationId );
 
            // We shouldn't use getValue() since that triggers recalculate() which would cause an infinite loop
            data[ calculationId ] = calculation.value;
        }


    mw.calculators.objectClasses.AbstractCalculation.prototype.getInfo = function( infoCount ) {
        var variables = calculationData.variables.required.concat( calculationData.variables.optional );
        var infoHtml = '';


         var description = this.getDescription();
         for( var iRequiredVariable in variables ) {
            variableId = variables[ iRequiredVariable ];
            variable = mw.calculators.getVariable( variableId );


        if( description ) {
             data[ variableId ] = variable.getValue();
             infoHtml += $( '<p>', {
                html: description
            } )[ 0 ].outerHTML;
         }
         }


         var formula = this.getFormula();
         return data;
    };


        if( formula ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.getClassName = function() {
            infoHtml += $( '<div>', {
        throw new Error( 'AbstractCalculation child class must implement getClassName()' );
                class: this.getElementClasses( 'formula' )
    };
            } )[ 0 ].outerHTML;
        }


         var references = this.getReferences();
    mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerClasses = function() {
         return this.getElementClasses();
    };


        if( references.length ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerId = function() {
            var $references = $( '<ol>' );
        return this.getElementPrefix() + '-' + this.id;
    };


            for( var iReference in references ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.getDescription = function() {
                $references.append( $( '<li>', {
        return this.description;
                    html: references[ iReference ]
    };
                } ) );
            }


            infoHtml += $( '<div>', {
    mw.calculators.objectClasses.AbstractCalculation.prototype.getElementPrefix = function( useClassName ) {
                class: this.getElementClasses( 'references' )
        var elementPrefix = 'calculator-';
            } ).append( $references )[ 0 ].outerHTML;
        }


         var infoContainerId = this.getContainerId() + '-info';
         elementPrefix += useClassName ? this.getClassName() : 'calculation';


         if( infoCount ) {
         return elementPrefix;
            infoContainerId += '-' + infoCount;
    };
        }


        $infoContainer = $( '<div>', {
    mw.calculators.objectClasses.AbstractCalculation.prototype.getElementClasses = function( elementId ) {
            id: infoContainerId,
        elementId = elementId ? '-' + elementId : '';
            class: 'collapse row no-gutters border-top ' + this.getElementClasses( 'info' )
        } ).append( infoHtml );


         return $infoContainer;
         return this.getElementPrefix() + elementId + ' ' +
            this.getElementPrefix( true ) + elementId + ' ' +
            this.getContainerId() + elementId;
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.getInfoButton = function( infoCount ) {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getFormula = function() {
         var infoContainerId = this.getContainerId() + '-info';
         return this.formula;
    };


        if( infoCount ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.getInfo = function( infoCount ) {
            infoContainerId += '-' + infoCount;
        var infoHtml = '';
        }


         return $( '<span>', {
         var description = this.getDescription();
            class: this.getElementClasses( 'infoButton' )
        } )
            .append( $( '<a>', {
                'data-toggle': 'collapse',
                href: '#' + infoContainerId,
                role: 'button',
                'aria-expanded': 'false',
                'aria-controls': infoContainerId
            } )
                .append( $( '<i>', {
                    class: 'far fa-question-circle'
                } ) ) );
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getMissingRequiredData = function() {
        if( description ) {
        var calculationData = this.getCalculationData();
            infoHtml += $( '<p>', {
                html: description
            } )[ 0 ].outerHTML;
        }


         var missingRequiredData = [];
         var formula = this.getFormula();
        var calculation, variable;


         for( var iRequiredCalculation in calculationData.calculations.required ) {
         if( formula ) {
             calculation = mw.calculators.getCalculation( calculationData.calculations.required[ iRequiredCalculation ] );
             infoHtml += $( '<div>', {
                class: this.getElementClasses( 'formula' )
            } )[ 0 ].outerHTML;
        }


            if( !calculation.hasValue() ) {
        var references = this.getReferences();
                missingRequiredData = missingRequiredData.concat( calculation.getMissingRequiredData() );
            }
        }


         for( var iRequiredVariable in calculationData.variables.required ) {
         if( references.length ) {
             variable = mw.calculators.getVariable( calculationData.variables.required[ iRequiredVariable ] );
             var $references = $( '<ol>' );


             if( !variable.hasValue() ) {
             for( var iReference in references ) {
                 missingRequiredData.push( String( variable ) );
                 $references.append( $( '<li>', {
                    html: references[ iReference ]
                } ) );
             }
             }
            infoHtml += $( '<div>', {
                class: this.getElementClasses( 'references' )
            } ).append( $references )[ 0 ].outerHTML;
         }
         }


         return missingRequiredData.filter( mw.calculators.uniqueValues );
         var infoContainerId = this.getContainerId() + '-info';
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties = function() {
        if( infoCount ) {
         return {
            infoContainerId += '-' + infoCount;
            required: [
         }
                'id',
 
                'calculate'
        $infoContainer = $( '<div>', {
             ],
             id: infoContainerId,
             optional: [
             class: 'collapse row no-gutters border-top ' + this.getElementClasses( 'info' )
                'data',
         } ).append( infoHtml );
                'description',
                'formula',
                'onRender',
                'onRendered',
                'references',
                'searchData',
                'type'
            ]
         };
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getReferences = function() {
         return $infoContainer;
         return this.references;
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.getSearchString = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getInfoButton = function( infoCount ) {
         var searchString = this.id;
         var infoContainerId = this.getContainerId() + '-info';


         searchString += this.searchData ? ' ' + this.searchData : '';
         if( infoCount ) {
            infoContainerId += '-' + infoCount;
        }


         return searchString.trim();
         return $( '<span>', {
            class: this.getElementClasses( 'infoButton' )
        } )
            .append( $( '<a>', {
                'data-toggle': 'collapse',
                href: '#' + infoContainerId,
                role: 'button',
                'aria-expanded': 'false',
                'aria-controls': infoContainerId
            } )
                .append( $( '<i>', {
                    class: 'far fa-question-circle'
                } ) ) );
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.getTitleHtml = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getMissingRequiredData = function() {
         return this.getTitleString();
         var calculationData = this.getCalculationData();
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getTitleString = function() {
        var missingRequiredData = [];
         return this.id;
         var calculation, variable;
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getValue = function() {
        for( var iRequiredCalculation in calculationData.calculations.required ) {
        // For now, we always need to recalculate, since the calculation may not be rendered but still required by
            calculation = mw.calculators.getCalculation( calculationData.calculations.required[ iRequiredCalculation ] );
        // other calculations (i.e. drug dosages using lean body weight).
        this.recalculate();


        return this.value;
            if( !calculation.hasValue() ) {
    };
                missingRequiredData = missingRequiredData.concat( calculation.getMissingRequiredData() );
            }
        }


    mw.calculators.objectClasses.AbstractCalculation.prototype.hasInfo = function() {
        for( var iRequiredVariable in calculationData.variables.required ) {
        return this.getDescription() || this.getFormula() || this.getReferences().length;
            variable = mw.calculators.getVariable( calculationData.variables.required[ iRequiredVariable ] );
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.hasValue = function() {
            if( !variable.hasValue() ) {
        if( this.value === null ||
                missingRequiredData.push( String( variable ) );
            ( this.isValueMathObject() && !this.value.toNumber() ) ) {
             }
             return false;
         }
         }


         return true;
         return missingRequiredData.filter( mw.calculators.uniqueValues );
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.initialize = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties = function() {
         if( typeof this.calculate !== 'function' ) {
         return {
            throw new Error( 'calculate() must be a function for Calculation "' + this.id + '"' );
            required: [
        }
                'id',
                'calculate'
            ],
            optional: [
                'data',
                'description',
                'formula',
                'onRender',
                'onRendered',
                'references',
                'searchData',
                'type'
            ]
        };
    };


        // Initialize array to store calculation ids which depend on this calculation's value
    mw.calculators.objectClasses.AbstractCalculation.prototype.getReferences = function() {
         this.calculations = [];
         return this.references;
    };


        this.data = new mw.calculators.objectClasses.CalculationData( this.getCalculationData() );
    mw.calculators.objectClasses.AbstractCalculation.prototype.getSearchString = function() {
        var searchString = this.id;


         this.references = this.references ? mw.calculators.prepareReferences( this.references ) : [];
         searchString += this.searchData ? ' ' + this.searchData : '';


         this.type = this.type ? this.type : TYPE_NUMBER;
         return searchString.trim();
    };


        this.message = null;
    mw.calculators.objectClasses.AbstractCalculation.prototype.getTitleHtml = function() {
         this.value = null;
         return this.getTitleString();
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.isValueMathObject = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getTitleString = function() {
         return mw.calculators.isValueMathObject( this.value );
         return this.id;
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.parseFormula = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getValue = function() {
         var formula = this.getFormula();
         // For now, we always need to recalculate, since the calculation may not be rendered but still required by
        // other calculations (i.e. drug dosages using lean body weight).
        this.recalculate();


         if( !formula ) {
         return this.value;
            return;
    };
        }


         var api = new mw.Api();
    mw.calculators.objectClasses.AbstractCalculation.prototype.hasInfo = function() {
         return this.getDescription() || this.getFormula() || this.getReferences().length;
    };


         var containerId = this.getContainerId() + '-formula';
    mw.calculators.objectClasses.AbstractCalculation.prototype.hasValue = function() {
         if( this.value === null ||
            ( this.isValueMathObject() && !this.value.toNumber() ) ) {
            return false;
        }


         api.parse( formula ).then( function( result ) {
         return true;
            $( '.' + containerId ).html( result );
        } );
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.recalculate = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.initialize = function() {
         this.message = '';
         if( typeof this.calculate !== 'function' ) {
        this.value = null;
            throw new Error( 'calculate() must be a function for Calculation "' + this.id + '"' );
        }


         var data = this.getCalculationDataValues();
         // Initialize array to store calculation ids which depend on this calculation's value
        this.calculations = [];


         if( data === false ) {
         this.data = new mw.calculators.objectClasses.CalculationData( this.getCalculationData() );
            this.valueUpdated();


            return false;
        this.references = this.references ? mw.calculators.prepareReferences( this.references ) : [];
        }


         try {
         this.type = this.type ? this.type : TYPE_NUMBER;
            var value = this.calculate( data );


            if( this.type === TYPE_NUMBER && !isNaN( value ) ) {
        this.message = null;
                if( this.units ) {
        this.value = null;
                    value = value + ' ' + this.units;
                }


                this.value = math.unit( value );
        // Remove any placeholder content explicitly set in the markup (used for SEO).
            } else {
        $( '.' + this.getContainerId() ).empty();
                this.value = value;
    };
            }
      } catch( e ) {
            console.warn( e.message );


            this.message = e.message;
    mw.calculators.objectClasses.AbstractCalculation.prototype.isValueMathObject = function() {
            this.value = null;
         return mw.calculators.isValueMathObject( this.value );
         } finally {
            this.valueUpdated();
        }
 
        return true;
     };
     };


    mw.calculators.objectClasses.AbstractCalculation.prototype.parseFormula = function() {
        var formula = this.getFormula();


 
         if( !formula ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
             return;
        this.recalculate();
 
         if( typeof this.onRender === 'function' ) {
             this.onRender();
         }
         }


         this.doRender();
         var api = new mw.Api();


         // Send API queries to parse LaTeX formulas
         var containerId = this.getContainerId() + '-formula';
        this.parseFormula();


         if( typeof this.onRendered === 'function' ) {
         api.parse( formula ).then( function( result ) {
             this.onRendered();
             $( '.' + containerId ).html( result );
         }
         } );
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.setDependencies = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.recalculate = function() {
         this.data = this.getCalculationData();
         this.message = '';
        this.value = null;


         var calculationIds = this.data.calculations.required.concat( this.data.calculations.optional );
         var data = this.getCalculationDataValues();


         for( var iCalculationId in calculationIds ) {
         if( data === false ) {
             var calculationId = calculationIds[ iCalculationId ];
             this.valueUpdated();


             if( !mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
             return false;
                throw new Error('Calculation "' + calculationId + '" does not exist for calculation "' + this.id + '"');
            }
 
            mw.calculators.calculations[ calculationId ].addCalculation( this.id );
         }
         }


         var variableIds = this.data.variables.required.concat( this.data.variables.optional );
         try {
            var value = this.calculate( data );


        for( var iVariableId in variableIds ) {
            if( this.type === TYPE_NUMBER && !isNaN( value ) ) {
            var variableId = variableIds[ iVariableId ];
                if( this.units ) {
                    value = value + ' ' + this.units;
                }


            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                this.value = math.unit( value );
                 throw new Error('Variable "' + variableId + '" does not exist for calculation "' + this.id + '"');
            } else {
                 this.value = value;
             }
             }
      } catch( e ) {
            console.warn( e.message );


             mw.calculators.variables[ variableId ].addCalculation( this.id );
             this.message = e.message;
            this.value = null;
        } finally {
            this.valueUpdated();
         }
         }


         this.recalculate();
         return true;
     };
     };


    mw.calculators.objectClasses.AbstractCalculation.prototype.toString = function() {
        return this.getTitleString();
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.valueUpdated = function() {
        for( var iCalculation in this.calculations ) {
            calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );


             if( calculation ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
                 calculation.render();
        // Need to run rendering in setTimeout to allow browser events to remain responsive
        var calculation = this;
 
        setTimeout( function() {
             if( typeof calculation.onRender === 'function' ) {
                 calculation.onRender();
             }
             }
        }
    };


            calculation.doRender();
            // Send API queries to parse LaTeX formulas
            calculation.parseFormula();


            mw.track( 'mw.calculators.CalculationRendered' );


    /**
            if( typeof calculation.onRendered === 'function' ) {
    * Class CalculationData
                calculation.onRendered();
    * @param {Object} propertyValues
            }
    * @returns {mw.calculators.objectClasses.CalculationData}
        }, 0 );
    * @constructor
    };
    */
    mw.calculators.objectClasses.CalculationData = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


        var dataTypes = this.getDataTypes();
    mw.calculators.objectClasses.AbstractCalculation.prototype.setDependencies = function() {
         var dataRequirements = this.getDataRequirements();
         this.data = this.getCalculationData();


         // Iterate through the supported data types (e.g. calculation, variable) to initialize the structure
         var calculationIds = this.data.calculations.required.concat( this.data.calculations.optional );
        for( var iDataType in dataTypes ) {
            var dataType = dataTypes[ iDataType ];


            if( !this[ dataType ] ) {
        for( var iCalculationId in calculationIds ) {
                this[ dataType ] = {
            var calculationId = calculationIds[ iCalculationId ];
                    optional: [],
                    required: []
                };
            } else {
                // Iterate through the requirement levels (i.e. optional, required) to initialize the structure
                for( var iDataRequirement in dataRequirements ) {
                    var dataRequirement = dataRequirements[ iDataRequirement ];


                    // FYI can't check to see if the data actually exists here since it may not be defined yet
            if( !mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
                    if( !this[ dataType ].hasOwnProperty( dataRequirement ) ) {
                throw new Error('Calculation "' + calculationId + '" does not exist for calculation "' + this.id + '"');
                        this[ dataType ][ dataRequirement ] = [];
                    }
                }
             }
             }
            mw.calculators.calculations[ calculationId ].addCalculation( this.id );
         }
         }
    };


    mw.calculators.objectClasses.CalculationData.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        var variableIds = this.data.variables.required.concat( this.data.variables.optional );
 
        for( var iVariableId in variableIds ) {
            var variableId = variableIds[ iVariableId ];


    mw.calculators.objectClasses.CalculationData.prototype.getDataRequirements = function() {
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
        return [
                throw new Error('Variable "' + variableId + '" does not exist for calculation "' + this.id + '"');
            'optional',
             }
             'required'
 
        ];
            mw.calculators.variables[ variableId ].addCalculation( this.id );
    };
        }


    mw.calculators.objectClasses.CalculationData.prototype.getDataTypes = function() {
        this.recalculate();
        return [
            'calculations',
            'variables'
        ];
     };
     };


     mw.calculators.objectClasses.CalculationData.prototype.getProperties = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.toString = function() {
         return {
         return this.getTitleString();
            required: [],
            optional: [
                'calculations',
                'variables'
            ]
        };
     };
     };


    mw.calculators.objectClasses.AbstractCalculation.prototype.update = function() {
        this.recalculate();


        this.render();
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.valueUpdated = function() {
        for( var iCalculation in this.calculations ) {
            calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );


    mw.calculators.objectClasses.CalculationData.prototype.merge = function() {
             if( calculation ) {
        var mergedData = new mw.calculators.objectClasses.CalculationData();
                 calculation.update();
 
        var data = [ this ].concat( Array.prototype.slice.call( arguments ) );
 
        var dataTypes = this.getDataTypes();
 
        for( var iData in data ) {
             for( var iDataType in dataTypes ) {
                 var dataType = dataTypes[ iDataType ];
 
                mergedData[ dataType ].required = mergedData[ dataType ].required
                    .concat( data[ iData ][ dataType ].required )
                    .filter( mw.calculators.uniqueValues );
 
                mergedData[ dataType ].optional = mergedData[ dataType ].optional
                    .concat( data[ iData ][ dataType ].optional )
                    .filter( mw.calculators.uniqueValues );
             }
             }
         }
         }
        return mergedData;
     };
     };






     /**
     /**
     * Class SimpleCalculation
     * Class CalculationData
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.SimpleCalculation}
     * @returns {mw.calculators.objectClasses.CalculationData}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.SimpleCalculation = function( propertyValues ) {
     mw.calculators.objectClasses.CalculationData = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


         this.initialize();
         var dataTypes = this.getDataTypes();
    };
        var dataRequirements = this.getDataRequirements();


    mw.calculators.objectClasses.SimpleCalculation.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculation.prototype );
        // Iterate through the supported data types (e.g. calculation, variable) to initialize the structure
        for( var iDataType in dataTypes ) {
            var dataType = dataTypes[ iDataType ];


    mw.calculators.objectClasses.SimpleCalculation.prototype.doRender = function() {
            if( !this[ dataType ] ) {
        var $calculationContainer = $( '.' + this.getContainerId() );
                this[ dataType ] = {
                    optional: [],
                    required: []
                };
            } else {
                // Iterate through the requirement levels (i.e. optional, required) to initialize the structure
                for( var iDataRequirement in dataRequirements ) {
                    var dataRequirement = dataRequirements[ iDataRequirement ];


        if( !$calculationContainer.length ) {
                    // FYI can't check to see if the data actually exists here since it may not be defined yet
             return;
                    if( !this[ dataType ].hasOwnProperty( dataRequirement ) ) {
         }
                        this[ dataType ][ dataRequirement ] = [];
                    }
                }
             }
         }
    };


        // Add all required classes
    mw.calculators.objectClasses.CalculationData.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        $calculationContainer.addClass( 'border ' + this.getContainerClasses() );


         // Add search phrases
    mw.calculators.objectClasses.CalculationData.prototype.getDataRequirements = function() {
        $calculationContainer.attr( 'data-search', this.getSearchString() );
         return [
            'optional',
            'required'
        ];
    };


         // Get a string version of the calculation's value
    mw.calculators.objectClasses.CalculationData.prototype.getDataTypes = function() {
         var valueString = this.getValueString();
         return [
            'calculations',
            'variables'
         ];
    };


        // We will need to show variable inputs for non-global variable inputs.
    mw.calculators.objectClasses.CalculationData.prototype.getProperties = function() {
        // Global inputs (i.e. those in the header) will claim the DOM id for that variable.
         return {
        // Non-global inputs (i.e. specific to a calculation) will only set a class but not the id,
            required: [],
         // and thus will get added to each calculation even if a duplicate.
            optional: [
        // E.g. 2 calculation might use the current hematocrit, but we should show them for both calculations since
                'calculations',
        // it wouldn't be obvious the input that only showed the first time would apply to both calculations.
                'variables'
         var inputVariableIds = this.data.variables.required.concat( this.data.variables.optional );
            ]
        var missingVariableInputs = [];
         };
    };


        for( var iInputVariableId in inputVariableIds ) {
            var variableId = inputVariableIds[ iInputVariableId ];


            if( !$( '#calculator-input-' + variableId ).length ) {
                missingVariableInputs.push( variableId );
            }
        }


        // Out of 12, uses Bootstrap col- classes in a container
        var titleColumns = '7';
        var valueColumns = '5';


        // Store this object in a local variable since .each() will reassign this to the DOM object of each
    mw.calculators.objectClasses.CalculationData.prototype.merge = function() {
        // calculation container.
         var mergedData = new mw.calculators.objectClasses.CalculationData();
         var calculation = this;
        var calculationCount = 0;


         // Eventually may implement different rendering, so we should regenerate
         var data = [ this ].concat( Array.prototype.slice.call( arguments ) );
        // all elements with each iteration of the loop.
        // I.e. might show result in table and inline in 2 different places of article.
        $calculationContainer.each( function() {
            // Initalize the variables for all the elements of the calculation. These need to be in order of placement
            // in the calculation container
            var elementTypes = [
                'title',
                'variables',
                'value',
                'info'
            ];


            var elements = {};
        var dataTypes = this.getDataTypes();


             for( var iElementType in elementTypes ) {
        for( var iData in data ) {
                 var elementType = elementTypes[ iElementType ];
             for( var iDataType in dataTypes ) {
                 var dataType = dataTypes[ iDataType ];


                 elements[ elementType ] = {
                 mergedData[ dataType ].required = mergedData[ dataType ].required
                     $container: null,
                     .concat( data[ iData ][ dataType ].required )
                     id: calculation.getContainerId() + '-' + elementType
                     .filter( mw.calculators.uniqueValues );
                };


                 if( calculationCount ) {
                 mergedData[ dataType ].optional = mergedData[ dataType ].optional
                     elements[ elementType ].id += '-' + calculationCount;
                    .concat( data[ iData ][ dataType ].optional )
                }
                     .filter( mw.calculators.uniqueValues );
             }
             }
        }


            // Create title element and append to container
        return mergedData;
            elements.title.$container = $( '<div>', {
    };
                id: elements.title.id
            } );


            elements.title.$container.append( calculation.getTitleHtml() );


            if( calculation.hasInfo() ) {
                elements.title.$container.append( calculation.getInfoButton( calculationCount ) );


                // Id of the info container should already be set by getInfo()
                elements.info.$container = calculation.getInfo();
            }


            // Create the value element
            elements.value.$container = $( '<div>', {
                class: 'col-' + valueColumns + ' ' + calculation.getElementClasses( 'value' )
            } ).append( valueString );


            if( !missingVariableInputs.length ) {
    /**
                // If we have no variable inputs to show, we can put the title and value in one row of the table
    * Class SimpleCalculation
                elements.title.$container.addClass( 'col-' + titleColumns + ' border-right' );
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.SimpleCalculation}
    * @constructor
    */
    mw.calculators.objectClasses.SimpleCalculation = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


                // Add the id attribute to the value container
        this.initialize();
                elements.value.$container.attr( 'id', elements.value.id );
    };
            } else {
                // If we need to show variable inputs, make the title span the full width of the container,
                // put the variable inputs on a new row, and show the result on a row below that.
                elements.title.$container.addClass( 'col-12 border-bottom' );


                // Create a new row for the variable inputs
    mw.calculators.objectClasses.SimpleCalculation.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculation.prototype );
                elements.variables.$container = $( '<div>', {
                    class: 'row no-gutters border-bottom ' + calculation.getElementClasses( 'variables' ),
                    id: elements.variables.id
                } )
                    .append( $( '<div>', {
                        class: 'col-12'
                    } )
                        .append( mw.calculators.createInputGroup( missingVariableInputs ) ) );


                elements.value.$container = $( '<div>', {
    mw.calculators.objectClasses.SimpleCalculation.prototype.doRender = function() {
                    class: 'row no-gutters',
        var $calculationContainer = $( '.' + this.getContainerId() );
                    id: elements.value.id
                } )
                    .append(
                        $( '<div>', {
                            class: 'col-' + titleColumns,
                            html: '&nbsp;'
                        } ),
                        elements.value.$container
                );
            }


            // Add the title classes after the layout classes
        if( !$calculationContainer.length ) {
            elements.title.$container.addClass( calculation.getElementClasses( 'title' ) );
            return;
        }


            // Iterate over elementTypes since it is in order of rendering
        // Add all required classes
            for( var iElementType in elementTypes ) {
        $calculationContainer.addClass( 'row no-gutters border ' + this.getContainerClasses() );
                var elementType = elementTypes[ iElementType ];


                var $existingContainer = $( '#' + elements[ elementType ].id );
        // Add search phrases
        $calculationContainer.attr( 'data-search', this.getSearchString() );


                if( $existingContainer.length ) {
        // Get a string version of the calculation's value
                    // If an input within this container has focus (i.e. the user changed a variable input which
        var valueString = this.getValueString();
                    // triggered this rerender), don't rerender the element as this would destroy the focus on
                    // the input.
                    if( !$.contains( $existingContainer[ 0 ], $( ':focus' )[ 0 ] ) ) {
                        $existingContainer.replaceWith( elements[ elementType ].$container );
                    }
                } else {
                    $( this ).append( elements[ elementType ].$container );
                }
            }


            calculationCount++;
        // We will need to show variable inputs for non-global variable inputs.
         } );
        // Global inputs (i.e. those in the header) will claim the DOM id for that variable.
    };
        // Non-global inputs (i.e. specific to a calculation) will only set a class but not the id,
        // and thus will get added to each calculation even if a duplicate.
        // E.g. 2 calculation might use the current hematocrit, but we should show them for both calculations since
        // it wouldn't be obvious the input that only showed the first time would apply to both calculations.
        var inputVariableIds = this.data.variables.required.concat( this.data.variables.optional );
        var missingVariableInputs = [];
 
         for( var iInputVariableId in inputVariableIds ) {
            var variableId = inputVariableIds[ iInputVariableId ];


    mw.calculators.objectClasses.SimpleCalculation.prototype.getClassName = function() {
            if( !$( '#calculator-input-' + variableId ).length ) {
         return 'SimpleCalculation';
                missingVariableInputs.push( variableId );
    };
            }
         }


    mw.calculators.objectClasses.SimpleCalculation.prototype.getProperties = function() {
        // Out of 12, uses Bootstrap col- classes in a container
         var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();
        var titleColumns = '7';
         var valueColumns = '5';


         return this.mergeProperties( inheritedProperties, {
         // Store this object in a local variable since .each() will reassign this to the DOM object of each
            required: [
        // calculation container.
                'name'
         var calculation = this;
            ],
        var calculationCount = 0;
            optional: [
                'abbreviation',
                'digits',
                'link',
                'units'
            ]
         } );
    };


    mw.calculators.objectClasses.SimpleCalculation.prototype.getSearchString = function() {
        // Eventually may implement different rendering, so we should regenerate
        return ( this.id + ' ' + this.abbreviation + ' ' + this.name + ' ' + this.searchData ).trim();
        // all elements with each iteration of the loop.
    };
        // I.e. might show result in table and inline in 2 different places of article.
        $calculationContainer.each( function() {
            // Initalize the variables for all the elements of the calculation. These need to be in order of placement
            // in the calculation container
            var elementTypes = [
                'title',
                'variables',
                'value',
                'info'
            ];


    mw.calculators.objectClasses.SimpleCalculation.prototype.getTitleHtml = function() {
            var elements = {};
        var titleHtml = this.getTitleString();


        if( this.link ) {
            for( var iElementType in elementTypes ) {
            var href = this.link;
                var elementType = elementTypes[ iElementType ];


            // Detect internal links (this isn't great)
                elements[ elementType ] = {
            var matches = href.match( /\[\[(.*?)\]\]/ );
                    $container: null,
                    id: calculation.getContainerId() + '-' + elementType
                };


            if( matches ) {
                if( calculationCount ) {
                href = mw.util.getUrl( matches[ 1 ] );
                    elements[ elementType ].id += '-' + calculationCount;
                }
             }
             }


             titleHtml = $( '<a>', {
             // Create title element and append to container
                 href: href,
            elements.title.$container = $( '<div>', {
                text: titleHtml
                 id: elements.title.id
             } )[ 0 ].outerHTML;
             } );
        }


        return titleHtml;
            elements.title.$container.append( calculation.getTitleHtml() );
    };


    mw.calculators.objectClasses.SimpleCalculation.prototype.getTitleString = function() {
            if( calculation.hasInfo() ) {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
                elements.title.$container.append( calculation.getInfoButton( calculationCount ) );
    };


    mw.calculators.objectClasses.SimpleCalculation.prototype.getValueString = function() {
                // Id of the info container should already be set by getInfo()
        if( this.message ) {
                elements.info.$container = calculation.getInfo();
            return this.message;
             }
        } else if( typeof this.value === 'object' && this.value.hasOwnProperty( 'value' ) ) {
            return mw.calculators.getValueString( this.value );
        } else {
             return String( this.value );
        }
    };


            // Create the value element
            elements.value.$container = $( '<div>' ).append( valueString );


            if( !missingVariableInputs.length ) {
                // If we have no variable inputs to show, we can put the title and value in one row of the table
                elements.title.$container.addClass( 'col-' + titleColumns + ' border-right' );


                // Add the id attribute to the value container
                elements.value.$container.attr( 'id', elements.value.id );


                elements.value.$container.addClass( 'col-' + valueColumns );
            } else {
                // If we need to show variable inputs, make the title span the full width of the container,
                // put the variable inputs on a new row, and show the result on a row below that.
                elements.title.$container.addClass( 'col-12 border-bottom' );
                elements.value.$container.addClass( 'col-12' );


    /**
                // Create a new row for the variable inputs
    * Class AbstractCalculator
                elements.variables.$container = $( '<div>', {
    * @param {Object} propertyValues
                    class: 'row no-gutters border-bottom ' + calculation.getElementClasses( 'variables' ),
    * @returns {mw.calculators.objectClasses.AbstractCalculator}
                    id: elements.variables.id
    * @constructor
                } )
    */
                    .append( $( '<div>', {
    mw.calculators.objectClasses.AbstractCalculator = function( propertyValues ) {
                        class: 'col-12'
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
                    } )
    };
                        .append( mw.calculators.createInputGroup( missingVariableInputs ) ) );


    mw.calculators.objectClasses.AbstractCalculator.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                elements.value.$container = $( '<div>', {
                    class: 'row no-gutters',
                    id: elements.value.id
                } )
                    .append(
                        elements.value.$container
                );
            }


    mw.calculators.objectClasses.AbstractCalculator.prototype.doRender = function() {
            // Add the title classes after the layout classes
        var $calculatorContainer = $( '.' + this.getContainerId() );
            elements.title.$container.addClass( calculation.getElementClasses( 'title' ) );


        if( !$calculatorContainer.length ) {
            elements.value.$container.addClass( calculation.getElementClasses( 'value' ) );
            return;
        }


        $calculatorContainer.addClass( this.getContainerClasses() );
            // Iterate over elementTypes since it is in order of rendering
 
            for( var iElementType in elementTypes ) {
        if( this.css ) {
                var elementType = elementTypes[ iElementType ];
            $calculatorContainer.css( this.css );
        }


        $calculatorContainer.attr( 'data-search', this.getSearchString() );
                var $existingContainer = $( '#' + elements[ elementType ].id );
        $calculatorContainer.attr( 'data-title', this.name );


        $calculatorContainer.empty();
                if( $existingContainer.length ) {
                    // If an input within this container has focus (i.e. the user changed a variable input which
                    // triggered this rerender), don't rerender the element as this would destroy the focus on
                    // the input.
                    if( !$.contains( $existingContainer[ 0 ], $( ':focus' )[ 0 ] ) ) {
                        $existingContainer.replaceWith( elements[ elementType ].$container );
                    }
                } else {
                    $( this ).append( elements[ elementType ].$container );
                }
            }


        $calculatorContainer.append( $( '<h4>', {
             calculationCount++;
             text: this.name
         } );
        } ) );
 
         var $calculationsContainer = $( '<div>' );
 
        $calculatorContainer.append( $calculationsContainer );
 
        for( var iCalculationId in this.calculations ) {
            var calculation = mw.calculators.getCalculation( this.calculations[ iCalculationId ] );
            var calculationContainerClass = 'row no-gutters ' + calculation.getContainerId();
 
            var $calculationContainer = $( '<div>', {
                class: calculationContainerClass
            } );
 
            $calculationsContainer.append( $calculationContainer );
 
            calculation.render();
        }
     };
     };


     mw.calculators.objectClasses.AbstractCalculator.prototype.getClassName = function() {
     mw.calculators.objectClasses.SimpleCalculation.prototype.getClassName = function() {
         throw new Error( 'AbstractCalculator child class must implement getClassName()' );
         return 'SimpleCalculation';
     };
     };


     mw.calculators.objectClasses.AbstractCalculator.prototype.getContainerClasses = function() {
     mw.calculators.objectClasses.SimpleCalculation.prototype.getProperties = function() {
         return this.getElementClasses();
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();
 
         return this.mergeProperties( inheritedProperties, {
            required: [
                'name'
            ],
            optional: [
                'abbreviation',
                'digits',
                'link',
                'units'
            ]
        } );
     };
     };


     mw.calculators.objectClasses.AbstractCalculator.prototype.getContainerId = function() {
     mw.calculators.objectClasses.SimpleCalculation.prototype.getSearchString = function() {
         return 'calculator-' + this.module + '-' + this.id;
         return ( this.id + ' ' + this.abbreviation + ' ' + this.name + ' ' + this.searchData ).trim();
     };
     };


     mw.calculators.objectClasses.AbstractCalculator.prototype.getElementPrefix = function( useClassName ) {
     mw.calculators.objectClasses.SimpleCalculation.prototype.getTitleHtml = function() {
         var elementPrefix = 'calculator-';
         var titleHtml = this.getTitleString();


         elementPrefix += useClassName ? this.getClassName() : 'calculator';
         if( this.link ) {
            var href = this.link;


        return elementPrefix;
            // Detect internal links (this isn't great)
    };
            var matches = href.match( /\[\[(.*?)\]\]/ );


    mw.calculators.objectClasses.AbstractCalculator.prototype.getElementClasses = function( elementId ) {
            if( matches ) {
        elementId = elementId ? '-' + elementId : '';
                href = mw.util.getUrl( matches[ 1 ] );
 
             }
        return this.getElementPrefix() + elementId + ' ' +
            this.getElementPrefix( true ) + elementId
             this.getContainerId() + elementId;
    };


    mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties = function() {
            titleHtml = $( '<a>', {
        return {
                 href: href,
            required: [
                 text: titleHtml
                'id',
             } )[ 0 ].outerHTML;
                 'module',
         }
                 'name',
                'calculations'
             ],
            optional: [
                'css',
                'onRender',
                'onRendered',
                'searchData'
            ]
         };
    };


    mw.calculators.objectClasses.AbstractCalculator.prototype.getSearchString = function() {
         return titleHtml;
        var searchString = this.id + ' ' + this.module + ' ' + this.name;
 
        searchString += this.searchData ? ' ' + this.searchData : '';
 
         return searchString.trim();
     };
     };


     mw.calculators.objectClasses.AbstractCalculator.prototype.getTitleString = function() {
     mw.calculators.objectClasses.SimpleCalculation.prototype.getTitleString = function() {
         return this.name;
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
     };
     };


     mw.calculators.objectClasses.AbstractCalculator.prototype.render = function() {
     mw.calculators.objectClasses.SimpleCalculation.prototype.getValueString = function() {
         mw.track( 'mw.calculators.CalculatorRender' );
         if( this.message ) {
 
            return this.message;
         if( typeof this.onRender === 'function' ) {
         } else if( typeof this.value === 'object' && this.value.hasOwnProperty( 'value' ) ) {
             this.onRender();
             return mw.calculators.getValueString( this.value );
        } else {
            return String( this.value );
         }
         }
        this.doRender();
        mw.track( 'mw.calculators.CalculatorRendered' );
        if( typeof this.onRendered === 'function' ) {
            this.onRendered();
        }
    };
    mw.calculators.objectClasses.AbstractCalculator.prototype.toString = function() {
        return this.getTitleString();
    };
    /**
    * Class SimpleCalculator
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.SimpleCalculator}
    * @constructor
    */
    mw.calculators.objectClasses.SimpleCalculator = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
    };
    mw.calculators.objectClasses.SimpleCalculator.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculator.prototype );
    mw.calculators.objectClasses.SimpleCalculator.prototype.getClassName = function() {
        return 'SimpleCalculator';
     };
     };



Latest revision as of 19:39, 5 April 2022

/**
 * @author Chris Rishel
 */
( function() {
    var COOKIE_EXPIRATION = 12 * 60 * 60;

    var TYPE_NUMBER = 'number';
    var TYPE_STRING = 'string';

    var VALID_TYPES = [
        TYPE_NUMBER,
        TYPE_STRING
    ];

    var DEFAULT_CALCULATION_CLASS = 'SimpleCalculation';

    // Polyfill to convert to roman numerals
    math.roman = function( number ) {
        var romanOrders = {
            M: 1000,
            CM: 900,
            D: 500,
            CD: 400,
            C: 100,
            XC: 90,
            L: 50,
            XL: 40,
            X: 10,
            IX: 9,
            V: 5,
            IV: 4,
            I: 1
        };

        var roman = '';

        for( var iOrder in romanOrders ) {
            var numOfOrder = Math.floor(number / romanOrders[ iOrder ] );
            number -= numOfOrder * romanOrders[ iOrder ];
            roman += iOrder.repeat( numOfOrder );
        }

        return roman;
    };

    // Polyfill to fetch unit's base. This may become unnecessary in a future version of math.js
    math.Unit.prototype.getBase = function() {
        for( var iBase in math.Unit.BASE_UNITS ) {
            if( this.equalBase( math.Unit.BASE_UNITS[ iBase ] ) ) {
                return iBase;
            }
        }

        return null;
    };


    mw.calculators = {
        calculations: {},
        objectClasses: {},
        options: {},
        selectors: {
            calculationCategories: '.calculator-calculationcategory',
            calculations: '.calculator-calculation',
            calculatorOptions: '.calculator-options'
        },
        units: {},
        unitsBases: {},
        variables: {},
        addCalculations: function( calculationData, className ) {
            className = className ? className : DEFAULT_CALCULATION_CLASS;

            var calculations = mw.calculators.createCalculatorObjects( className, calculationData );

            for( var calculationId in calculations ) {
                var calculation = calculations[ calculationId ];

                mw.calculators.calculations[ calculationId ] = calculation;

                mw.calculators.calculations[ calculationId ].setDependencies();

                mw.calculators.calculations[ calculationId ].update();
            }
        },
        addUnitsBases: function( unitsBaseData ) {
            var unitsBases = mw.calculators.createCalculatorObjects( 'UnitsBase', unitsBaseData );

            for( var unitsBaseId in unitsBases ) {
                mw.calculators.unitsBases[ unitsBaseId.toLowerCase() ] = unitsBases[ unitsBaseId ];
            }
        },
        addUnits: function( unitsData ) {
            var units = mw.calculators.createCalculatorObjects( 'Units', unitsData );

            for( var unitsId in units ) {
                if( mw.calculators.units.hasOwnProperty( unitsId ) ) {
                    continue;
                }

                var unitData = {
                    aliases: units[ unitsId ].aliases,
                    baseName: units[ unitsId ].baseName ? units[ unitsId ].baseName.toUpperCase() : units[ unitsId ].baseName,
                    definition: units[ unitsId ].definition,
                    prefixes: units[ unitsId ].prefixes,
                    offset: units[ unitsId ].offset
                };

                try {
                    math.createUnit( unitsId, unitData );
                } catch( e ) {
                    console.warn( e.message );
                }

                mw.calculators.units[ unitsId ] = units[ unitsId ];
            }
        },
        addVariables: function( variableData ) {
            var variables = mw.calculators.createCalculatorObjects( 'Variable', variableData );

            for( var variableId in variables ) {
                mw.calculators.variables[ variableId ] = variables[ variableId ];

                var cookieValue = mw.calculators.getCookieValue( variableId );

                if( cookieValue ) {
                    // Try to set the variable value from the cookie value
                    if( !mw.calculators.variables[ variableId ].setValue( cookieValue ) ) {
                        // Unset the cookie value since for whatever reason it's no longer valid.
                        mw.calculators.setCookieValue( variableId, null );
                    }
                }
            }
        },
        createCalculatorObjects: function( className, objectData ) {
            if( !mw.calculators.objectClasses.hasOwnProperty( className ) ) {
                throw new Error( 'Invalid class name "' + className + '"' );
            }

            var objects = {};

            for( var objectId in objectData ) {
                var propertyValues = objectData[ objectId ];

                // Id can either be specified using the 'id' property, or as the property name in objectData
                if( propertyValues.hasOwnProperty( 'id' ) ) {
                    objectId = propertyValues.id;
                }
                else {
                    propertyValues.id = objectId;
                }

                objects[ objectId ] = new mw.calculators.objectClasses[ className ]( propertyValues );
            }

            return objects;
        },
        createInputGroup: function( variableIds, global, maxInputsPerRow ) {
            var $form = $( '<form>', {
                novalidate: true
            } );

            var $formRow;

            var inputOptions = {
                global: !!global
            };

            maxInputsPerRow = maxInputsPerRow ?
                maxInputsPerRow :
                mw.calculators.getOptionValue( 'inputgroupmaxinputsperrow' );

            var inputCount = 0;

            for( var iVariableId in variableIds ) {
                var variableId = variableIds[ iVariableId ];

                if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                    throw new Error( 'Invalid variable name "' + variableId + '"' );
                }

                if( inputCount % maxInputsPerRow === 0 ) {
                    if( $formRow ) {
                        $form.append( $formRow );
                    }

                    $formRow = $( '<div>', {
                        class: 'form-row calculator-inputGroup'
                    } );
                }

                $formRow.append( mw.calculators.variables[ variableId ].createInput( inputOptions ) );

                inputCount++;
            }

            return $form.append( $formRow );
        },
        getCookieKey: function( variableId ) {
            return 'calculators-var-' + variableId;
        },
        getCookieValue: function( varId ) {
            var cookieValue = mw.cookie.get( mw.calculators.getCookieKey( varId ) );

            if( !cookieValue ) {
                return null;
            }

            return cookieValue;
        },
        getCalculation: function( calculationId ) {
            if( mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
                return mw.calculators.calculations[ calculationId ];
            } else {
                return null;
            }
        },
        getOptionValue: function( optionId ) {
            return mw.calculators.options.hasOwnProperty( optionId ) ?
                mw.calculators.options[ optionId ] :
                undefined;
        },
        getUnitsByBase: function( value ) {
            if( typeof value !== 'object' || !value.hasOwnProperty( 'units' ) ) {
                return null;
            }

            var unitsByBase = {};

            for( var iUnits in value.units ) {
                var units = value.units[ iUnits ];

                // Some units are of a given dimension, but have no conversion definition
                // (e.g. 'units' for mass, 'vial' for volume, etc.). These units are added
                // by appending '_abstract' to the baseName of the unit definition. However,
                // the calculator should treat them as the same type of unit
                var baseId = units.unit.base.key.toLowerCase().replace( /_\w+/, '' );

                unitsByBase[ baseId ] = units.prefix.name + units.unit.name;
            }

            return unitsByBase;
        },
        getUnitsString: function( value ) {
            if( typeof value !== 'object' ) {
                return null;
            }

            var unitsString = value.formatUnits();

            var reDenominator = /\/\s?\((.*)\)/;
            var denominatorMatches = unitsString.match( reDenominator );

            if( denominatorMatches ) {
                var denominatorUnits = denominatorMatches[ 1 ];

                unitsString = unitsString.replace( reDenominator, '/' + denominatorUnits.replace( ' ', '/' ) );
            }

            unitsString = unitsString
                .replace( /\s/g, '' )
                .replace( /(\^(\d+))/g, '<sup>$2</sup>' );

            var unitsBase = value.getBase();

            if( unitsBase ) {
                unitsBase = unitsBase.toLowerCase();

                if( mw.calculators.unitsBases.hasOwnProperty( unitsBase ) &&
                    typeof mw.calculators.unitsBases[ unitsBase ].toString === 'function' ) {
                    unitsString = mw.calculators.unitsBases[ unitsBase ].toString( unitsString );
                }
            } else {
                // TODO nasty hack to fix weight units in compound units which have no base
                unitsString = unitsString.replace( 'kgwt', 'kg' );
                unitsString = unitsString.replace( 'ug', 'mcg' );
            }

            return unitsString;
        },
        getValueDecimals: function( value ) {
            // Supports either numeric values or math objects
            if( mw.calculators.isValueMathObject( value ) ) {
                value = mw.calculators.getValueNumber( value );
            }

            if( typeof value !== 'number' ) {
                return null;
            }

            // Convert the number to a string, reverse, and count the number of characters up to the period.
            var decimals = value.toString().split('').reverse().join('').indexOf( '.' );

            // If no decimal is present, will be set to -1 by indexOf. If so, set to 0.
            decimals = decimals > 0 ? decimals : 0;

            return decimals;
        },
        getValueNumber: function( value, decimals ) {
            if( !mw.calculators.isValueMathObject( value ) ) {
                return null;
            }

            // Remove floating point errors
            var number = math.round( value.toNumber(), 10 );

            var absNumber = math.abs( number );

            if( absNumber >= 10 || absNumber === 0 ) {
                if( absNumber < 100 && absNumber !== math.round( absNumber ) && 2 * absNumber === math.round( 2 * absNumber ) ) {
                    // Special case to allow nearly-round decimals (e.g. 12.5)

                    decimals = 1;
                } else {
                    decimals = 0;
                }
            } else {
                decimals = -math.floor( math.log10( absNumber ) ) + 1;
            }

            return math.round( number, decimals );
        },
        getValueString: function( value, decimals ) {
            if( !mw.calculators.isValueMathObject( value ) ) {
                return null;
            }

            var valueNumber = mw.calculators.getValueNumber( value, decimals );
            var valueUnits = mw.calculators.getUnitsString( value );

            if( math.abs( math.log10( valueNumber ) ) > 3 ) {
                var valueUnitsByBase = mw.calculators.getUnitsByBase( value );

                var oldSIUnit;

                if( valueUnitsByBase.hasOwnProperty( 'mass' ) ) {
                    oldSIUnit = valueUnitsByBase.mass;
                } else if( valueUnitsByBase.hasOwnProperty( 'volume' ) ) {
                    oldSIUnit = valueUnitsByBase.volume;
                }

                if( oldSIUnit ) {
                    // This new value should simplify to the optimal SI prefix.
                    // We need to create a completely new unit from the formatted (i.e. simplified) value
                    var newSIValue = math.unit( math.unit( valueNumber + ' ' + oldSIUnit ).format() );

                    // There is a bug in mathjs where formatUnits() won't simplify the units, only format() will.
                    var newSIUnit = newSIValue.formatUnits();

                    if( newSIUnit !== oldSIUnit ) {
                        value = math.unit( newSIValue.toNumber() + ' ' + value.formatUnits().replace( oldSIUnit, newSIUnit ) );

                        valueNumber = mw.calculators.getValueNumber( value, decimals );
                        valueUnits = mw.calculators.getUnitsString( value );
                    }
                }
            }

            var valueString = String( valueNumber );

            if( valueUnits ) {
                valueString += ' ' + valueUnits;
            }

            var unitsId = value.formatUnits();

            if( mw.calculators.units.hasOwnProperty( unitsId ) &&
                typeof mw.calculators.units[ unitsId ].formatValue === 'function' ) {
                valueString = mw.calculators.units[ unitsId ].formatValue( valueString );
            }

            return valueString;
        },
        getVariable: function( variableId ) {
            if( mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return mw.calculators.variables[ variableId ];
            } else {
                return null;
            }
        },
        hasData: function( dataType, dataId ) {
            if( mw.calculators.hasOwnProperty( dataType ) &&
                mw.calculators[ dataType ].hasOwnProperty( dataId ) ) {
                return true;
            } else {
                return false;
            }
        },
        initialize: function() {
            // Change the menu item from "article" to "calculator"
            $( '#nav-article svg' ).addClass( 'fa-calculator' );
            $( '#nav-article .nav-label' ).html( 'Calculator' );

            // Wrap description in a collapse
            var descriptionCount = 0;

            $( '.calculator-description' ).each( function() {
                var descriptionContainerId = 'calculator-description-info';

                if( descriptionCount ) {
                    descriptionContainerId += '-' + descriptionCount;
                }

                var $descriptionLinkIcon = $( '<i>', {
                    class: 'far fa-question-circle fa-fw'
                } );

                var descriptionLinkString = '';

                descriptionLinkString += $( this ).data( 'title' ) ? $( this ).data( 'title' ) : 'About this calculator';

                var $descriptionLinkLabel = $( '<span>', {
                    html: descriptionLinkString
                } );

                var $descriptionLink = $( '<a>', {
                    'data-toggle': 'collapse',
                    href: '#' + descriptionContainerId,
                    role: 'button',
                    'aria-expanded': 'false',
                    'aria-controls': descriptionContainerId
                } ).append( $descriptionLinkIcon, $descriptionLinkLabel );

                var $descriptionContainer = $( '<div>', {
                    id: descriptionContainerId,
                    class: 'collapse calculator-description-info',
                    html: $( this ).html()
                } );

                $( this ).empty();

                if( !descriptionCount ) {
                    $descriptionLink.addClass( 'dropdown-item' );
                    $descriptionLinkLabel.addClass( 'nav-label' );

                    $('#menuButton .dropdown-menu').prepend( $descriptionLink );
                } else {
                    $descriptionLink.addClass( 'btn btn-outline-primary btn-sm' );
                    $( this ).append( $descriptionLink );
                }

                $( this ).append( $descriptionContainer );

                descriptionCount++;
            } );

            // Set options
            mw.calculators.setDefaultOptions();

            var $optionsElement = $( mw.calculators.selectors.calculatorOptions );
            if( $optionsElement.length ) {
                $.each( $optionsElement.data(), function( optionId, value ) {
                    mw.calculators.setOptionValue( optionId, value );
                } );
            }

            mw.hook( 'calculators.initialized' ).fire();
        },
        isMobile: function() {
            return window.matchMedia( 'only screen and (max-width: 760px)' ).matches;
        },
        isValueMathObject: function( value ) {
            return value && value.hasOwnProperty( 'value' );
        },
        prepareReferences: function( references ) {
            for( var iReference in references ) {
                var reference = references[ iReference ];

                // http(s)
                reference = reference.replace(
                    /(https?:\/\/[^\s]*)/gmi,
                    '<a href="$1" target="_blank">$1</a>'
                );

                // doi
                reference = reference.replace(
                    /doi: ([\w\d\.\/-]+)((\.\s)|$)/gmi,
                    'doi: <a href="https://doi.org/$1" target="_blank">$1</a>$2'
                );

                // PMCID
                reference = reference.replace(
                    /PMCID: PMC(\d+)/gmi,
                    'PMCID: <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC$1/" target="_blank">PMC$1</a>'
                );

                // PMID
                reference = reference.replace(
                    /PMID: (\d+)/gmi,
                    'PMID: <a href="https://pubmed.ncbi.nlm.nih.gov/$1" target="_blank">$1</a>'
                );

                references[ iReference ] = reference;
            }

            return references;
        },
        setCookieValue: function( variableId, value ) {
            mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
                expires: COOKIE_EXPIRATION
            } );
        },
        setDefaultOptions: function() {
            mw.calculators.setOptionValue( 'inputgroupmaxinputsperrow', 3 );
        },
        setOptionValue: function( optionId, value ) {
            mw.calculators.options[ optionId ] = value;

            return true;
        },
        setValue: function( variableId, value ) {
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return false;
            }

            if( !mw.calculators.variables[ variableId ].setValue( value ) ) {
                return false;
            }

            mw.calculators.setCookieValue( variableId, value );

            return true;
        },
        uniqueValues: function( value, index, self ) {
            return self.indexOf( value ) === index;
        }
    };

    /**
     * Class CalculatorObject
     *
     * @param {Object} properties
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.CalculatorObject}
     * @constructor
     */
    mw.calculators.objectClasses.CalculatorObject = function( properties, propertyValues ) {
        propertyValues = propertyValues ? propertyValues : {};

        if( properties ) {
            if( properties.hasOwnProperty( 'required' ) ) {
                for( var iRequiredProperty in properties.required ) {
                    var requiredProperty = properties.required[ iRequiredProperty ];

                    if( !propertyValues || !propertyValues.hasOwnProperty( requiredProperty ) ) {
                        console.error( 'Missing required property "' + requiredProperty + '"' );
                        console.log( propertyValues );

                        return null;
                    }

                    this[ requiredProperty ] = propertyValues[ requiredProperty ];

                    delete propertyValues[ requiredProperty ];
                }
            }

            if( properties.hasOwnProperty( 'optional' ) ) {
                for( var iOptionalProperty in properties.optional ) {
                    var optionalProperty = properties.optional[ iOptionalProperty ];

                    if( propertyValues && propertyValues.hasOwnProperty( optionalProperty ) ) {
                        this[ optionalProperty ] = propertyValues[ optionalProperty ];

                        delete propertyValues[ optionalProperty ];
                    } else if( typeof this[ optionalProperty ] === 'undefined' ) {
                        this[ optionalProperty ] = null;
                    }
                }
            }

            var invalidProperties = Object.keys( propertyValues );

            if( invalidProperties.length ) {
                console.warn( 'Unsupported properties defined for ' + typeof this + ' with id "' + this.id + '": ' + invalidProperties.join( ', ' ) );
            }
        }
    };

    mw.calculators.objectClasses.CalculatorObject.prototype.getProperties = function() {
        return {
            required: [],
            optional: []
        };
    };

    mw.calculators.objectClasses.CalculatorObject.prototype.mergeProperties = function( inheritedProperties, properties ) {
        var uniqueValues = function( value, index, self ) {
            return self.indexOf( value ) === index;
        };

        properties.required = inheritedProperties.required.concat( properties.required ).filter( uniqueValues );
        properties.optional = inheritedProperties.optional.concat( properties.optional ).filter( uniqueValues );

        return properties;
    };




    /**
     * Class UnitsBase
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.UnitsBase}
     * @constructor
     */
    mw.calculators.objectClasses.UnitsBase = function( propertyValues ) {
        var properties = {
            required: [
                'id'
            ],
            optional: [
                'toString'
            ]
        };

        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
    };

    mw.calculators.objectClasses.UnitsBase.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );




    /**
     * Class Units
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.Units}
     * @constructor
     */
    mw.calculators.objectClasses.Units = function( propertyValues ) {
        var properties = {
            required: [
                'id'
            ],
            optional: [
                'aliases',
                'baseName',
                'definition',
                'formatValue',
                'offset',
                'prefixes'
            ]
        };

        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
    };

    mw.calculators.objectClasses.Units.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );




    /**
     * Class Variable
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.Variable}
     * @constructor
     */
    mw.calculators.objectClasses.Variable = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );

        if( VALID_TYPES.indexOf( this.type ) === -1 ) {
            throw new Error( 'Invalid type "' + this.type + '" for variable "' + this.id + '"' );
        }

        // Accept options as either an array of strings, or an object with ids as keys and display text as values
        if( Array.isArray( this.options ) ) {
            var options = {};

            for( var iOption in this.options ) {
                var option = this.options[ iOption ];

                options[ option ] = option;
            }

            this.options = options;
        }

        this.calculations = [];

        if( this.defaultValue ) {
            this.defaultValue = this.prepareValue( this.defaultValue );
        }

        if( this.minValue ) {
            this.minValue = this.prepareValue( this.minValue );
        }

        if( this.maxValue ) {
            this.maxValue = this.prepareValue( this.maxValue );
        }

        this.message = null;
        this.valid = true;

        this.isValueSet = false;
        this.value = null;
    };

    mw.calculators.objectClasses.Variable.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );

    mw.calculators.objectClasses.Variable.prototype.addCalculation = function( calculationId ) {
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
            return;
        }

        this.calculations.push( calculationId );
    };

    mw.calculators.objectClasses.Variable.prototype.createInput = function( inputOptions ) {
        if( !inputOptions ) {
            inputOptions = {};
        }

        inputOptions.class = inputOptions.hasOwnProperty( 'class' ) ? inputOptions.class : '';
        inputOptions.global = inputOptions.hasOwnProperty( 'class' ) ? inputOptions.global : false;
        inputOptions.hideLabel = inputOptions.hasOwnProperty( 'hideLabel' ) ? inputOptions.hideLabel : false;
        inputOptions.hideLabelMobile = inputOptions.hasOwnProperty( 'hideLabelMobile' ) ? inputOptions.hideLabelMobile : false;
        inputOptions.inline = inputOptions.hasOwnProperty( 'inline' ) ? inputOptions.inline : false;
        inputOptions.inputClass = inputOptions.hasOwnProperty( 'inputClass' ) ? inputOptions.inputClass : '';

        var variableId = this.id;
        var inputId = 'calculator-input-' + variableId;

        // If not creating a global input, assign an iterated id
        if( !inputOptions.global ) {
            var inputIdCount = 0;

            while( $( '#' + inputId + '-' + inputIdCount ).length ) {
                inputIdCount++;
            }

            inputId += '-' + inputIdCount;
        }

        var inputContainerTag = inputOptions.inline ? '<span>' : '<div>';

        var inputContainerAttributes = {
            class: 'form-group mb-0 calculator-container-input'
        };

        inputContainerAttributes.class += inputOptions.class ? ' ' + inputOptions.class : '';
        inputContainerAttributes.class += ' calculator-container-input-' + variableId;

        var inputContainerCss = {};

        // Initialize label attributes
        var labelAttributes = {
            for: inputId,
            html: this.getLabelString()
        };

        if( inputOptions.hideLabel || ( inputOptions.hideLabelMobile && mw.calculators.isMobile() ) ) {
            labelAttributes.class = 'sr-only';
        }

        var labelCss = {};

        if( inputOptions.inline ) {
            inputContainerTag = '<span>';

            inputContainerCss[ 'align-items' ] = 'center';
            inputContainerCss[ 'display' ] = 'flex';
            //inputContainerCss[ 'height' ] = 'calc(1.5em + 0.75rem + 2px)';

            labelAttributes.html += ':&nbsp;';
            labelCss[ 'margin-bottom' ] = 0;
        }

        // Create the input container
        var $inputContainer = $( inputContainerTag, inputContainerAttributes ).css( inputContainerCss );

        var $label = $( '<label>', labelAttributes ).css( labelCss );

        $inputContainer.append( $label );

        // 'this' will be redefined for event handlers
        var variable = this;
        var value = this.getValue();

        if( this.type === TYPE_NUMBER ) {
            // Initialize the primary units variables (needed for handlers, even if doesn't have units)
            var unitsId = null;
            var $unitsContainer = null;

            var inputValue = '';

            if( mw.calculators.isValueMathObject( value ) ) {
                var number = value.toNumber();

                if( number ) {
                    inputValue = number;
                }
            } else {
                inputValue = value;
            }

            // Initialize input options
            var inputAttributes = {
                id: inputId,
                class: 'form-control form-control-sm calculator-input calculator-input-text',
                type: 'text',
                autocomplete: 'off',
                inputmode: 'decimal',
                value: inputValue
            };

            // Configure additional options
            if( this.maxLength ) {
                inputAttributes.maxlength = this.maxLength;
            }

            // Add any additional classes to the input
            inputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';

            // Add the input id to the list of classes
            inputAttributes.class += ' ' + inputId;

            // If the variable has units, create the units input
            if( this.hasUnits() ) {
                // Set the units id
                unitsId = inputId + '-units';

                var unitsValue = mw.calculators.isValueMathObject( value ) ? value.formatUnits() : null;

                var unitsInputAttributes = {
                    id: unitsId
                };

                // Create the units container
                $unitsContainer = $( '<div>', {
                    class: 'input-group-append'
                } ).css( 'align-items', 'center' );

                if( this.units.length === 1 ) {
                    unitsInputAttributes.type = 'hidden';
                    unitsInputAttributes.value = this.units[ 0 ];

                    $unitsContainer
                        .css( 'padding', '0 0.5em' )
                        .append( mw.calculators.getUnitsString( math.unit( '0 ' + this.units[ 0 ] ) ) )
                        .append( $( '<input>', unitsInputAttributes ) );
                } else {
                    // Initialize the units input options
                    unitsInputAttributes.class = 'custom-select custom-select-sm calculator-input-select';

                    // Add any additional classes to the input
                    unitsInputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';

                    unitsInputAttributes.class = unitsInputAttributes.class + ' ' + unitsId;

                    var $unitsInput = $( '<select>', unitsInputAttributes )
                        .on( 'change', function() {
                            var numberValue = $( '#' + inputId ).val();

                            var newValue = numberValue ? numberValue + ' ' + $( this ).val() : null;

                            if( !mw.calculators.setValue( variableId, newValue ) ) {
                                if( variable.message ) {
                                    $( this ).parent().parent().parent().find( '.invalid-feedback' ).html( variable.message );
                                }

                                $( this ).parent().parent().addClass( 'is-invalid' );
                            } else {
                                $( this ).parent().parent().removeClass( 'is-invalid' );
                            }
                        } );

                    for( var iUnits in this.units ) {
                        var units = this.units[ iUnits ];

                        var unitsOptionAttributes = {
                            html: mw.calculators.getUnitsString( math.unit( '0 ' + units ) ),
                            value: units
                        };

                        if( units === unitsValue ) {
                            unitsOptionAttributes.selected = true;
                        }

                        $unitsInput.append( $( '<option>', unitsOptionAttributes ) );
                    }

                    $unitsContainer.append( $unitsInput );
                }
            }

            // Create the input and add handlers
            var $input = $( '<input>', inputAttributes )
                .on( 'input', function() {
                    var numberValue = $( this ).val();

                    var newValue = numberValue ? numberValue : null;

                    if( newValue && unitsId ) {
                        newValue = newValue + ' ' + $( '#' + unitsId ).val();
                    }

                    if( !mw.calculators.setValue( variableId, newValue ) ) {
                        if( variable.message ) {
                            $( this ).parent().parent().find( '.invalid-feedback' ).html( variable.message );
                        }

                        $( this ).parent().addClass( 'is-invalid' );
                    } else {
                        $( this ).parent().removeClass( 'is-invalid' );
                    }
                } );

            // Create the input group
            var $inputGroup = $( '<div>', {
                class: 'input-group'
            } ).append( $input );

            if( $unitsContainer ) {
                $inputGroup.append( $unitsContainer );
            }

            $inputContainer.append( $inputGroup );
        } else if( this.type === TYPE_STRING ) {
            if( this.hasOptions() ) {
                var optionKeys = Object.keys( this.options );

                if( optionKeys.length === 1 ) {
                    $inputContainer.append( this.options[ optionKeys[ 0 ] ] );
                } else {
                    var selectAttributes = {
                        id: inputId,
                        class: 'custom-select custom-select-sm calculator-input calculator-input-select'
                    };

                    // Add any additional classes to the input
                    selectAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';

                    var $select = $( '<select>', selectAttributes )
                        .on( 'change', function() {
                            if( !mw.calculators.setValue( variableId, $( this ).val() ) ) {
                                if( variable.message ) {
                                    $( this ).parent().parent().find( '.invalid-feedback' ).html( variable.message );
                                }

                                $( this ).parent().addClass( 'is-invalid' );
                            } else {
                                $( this ).parent().removeClass( 'is-invalid' );
                            }

                        } );

                    for( var optionId in this.options ) {
                        var displayText = this.options[ optionId ];

                        var optionAttributes = {
                            value: optionId,
                            text: displayText
                        };

                        if( optionId == value ) {
                            optionAttributes.selected = true;
                        }

                        $select.append( $( '<option>', optionAttributes ) );
                    }

                    $inputContainer.append( $select );
                }
            }
        }

        if( $inputContainer.length ) {
            $inputContainer.append( $( '<div>', {
                class: 'invalid-feedback'
            } ) );
        }

        return $inputContainer;
    };

    mw.calculators.objectClasses.Variable.prototype.getLabelString = function() {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
    };

    mw.calculators.objectClasses.Variable.prototype.getProperties = function() {
        return {
            required: [
                'id',
                'name',
                'type'
            ],
            optional: [
                'abbreviation',
                'defaultValue',
                'maxLength',
                'maxValue',
                'minValue',
                'options',
                'units'
            ]
        };
    };

    mw.calculators.objectClasses.Variable.prototype.getValue = function() {
        if( !this.valid ) {
            return null;
        } else if( this.value !== null ) {
            return this.value;
        } else if( !this.isValueSet && this.defaultValue !== null ) {
            return this.defaultValue;
        } else {
            return null;
        }
    };

    mw.calculators.objectClasses.Variable.prototype.getValueString = function() {
        return String( this.getValue() );
    };

    mw.calculators.objectClasses.Variable.prototype.hasOptions = function() {
        return this.options !== null;
    };

    mw.calculators.objectClasses.Variable.prototype.hasUnits = function() {
        return this.units !== null;
    };

    mw.calculators.objectClasses.Variable.prototype.hasValue = function() {
        var value = this.getValue();

        if( value === null ||
            ( mw.calculators.isValueMathObject( value ) && !value.toNumber() ) ) {
            return false;
        }

        return true;
    };

    mw.calculators.objectClasses.Variable.prototype.isValueMathObject = function() {
        return mw.calculators.isValueMathObject( this.value );
    };

    mw.calculators.objectClasses.Variable.prototype.prepareValue = function( value ) {
        if( value !== null ) {
            if( this.type === TYPE_NUMBER ) {
                if( !mw.calculators.isValueMathObject( value ) ) {
                    value = math.unit( value );
                }
            }
        }

        return value;
    };

    mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
        // Set flag to prevent returning defaultValue in getValue()
        this.isValueSet = true;

        var validateResult = this.validateValue( value );

        this.valid = !!validateResult.valid;
        this.message = validateResult.message;

        if( !this.valid ) {
            this.value = null;
            this.valueUpdated();

            return false;
        }

        this.value = this.prepareValue( value );

        this.valueUpdated();

        return true;
    };

    mw.calculators.objectClasses.Variable.prototype.toString = function() {
        return this.getLabelString();
    };

    mw.calculators.objectClasses.Variable.prototype.validateValue = function( value ) {
        // Initialize valid flag to true. Will be set false if an error is found.
        result = {
            message: null,
            valid: true
        };

        // (At least for now) unsetting a variable is always valid
        if( value === null ) {
             return result;
        }

        // Some errors which are plausibly from normal user input we will show as feedback on the input (e.g.
        // a numeric value that is below the minimum value. Errors which are unlikely to be from user input
        // and instead relate to developer issues (e.g. incorrect units in select boxes), only show on the console.
        var consoleWarnPrefix = 'Could not set value "' + value + '" for "' + this.id + '":';

        if( this.type === TYPE_NUMBER ) {
            if( !mw.calculators.isValueMathObject( value ) ) {
                value = math.unit( value );
            }

            var valueUnits;

            if( this.hasUnits() ) {
                valueUnits = value.formatUnits().replace( /\s/g, '' );

                if( !valueUnits ) {
                    // Unlikely to be a user error, so don't set message.
                    result.valid = false;

                    console.warn( consoleWarnPrefix + 'Value must define units' );
                } else if( this.units.indexOf( valueUnits ) === -1 ) {
                    // Unlikely to be a user error, so don't set message.
                    result.valid = false;

                    console.warn( consoleWarnPrefix + 'Units "' + valueUnits + '" are not valid for this variable' );
                }
            }

            if( this.minValue && math.smaller( value, this.minValue ) ) {
                var minValueString = mw.calculators.getValueString( this.minValue );

                if( valueUnits && valueUnits != this.minValue.formatUnits() ) {
                    minValueString += ' (' + mw.calculators.getValueString( this.minValue.to( valueUnits ) ) + ')';
                }

                result.message = String( this ) + ' must be at least ' + minValueString;
                result.valid = false;
            } else if( this.maxValue && math.larger( value, this.maxValue ) ) {
                var maxValueString = mw.calculators.getValueString( this.maxValue );

                if( valueUnits && valueUnits != this.maxValue.formatUnits() ) {
                    maxValueString += ' (' + mw.calculators.getValueString( this.maxValue.to( valueUnits ) ) + ')';
                }

                result.message = String( this ) + ' must be less than ' + maxValueString;
                result.valid = false;
            }
        } else if( this.hasOptions() ) {
            if( !this.options.hasOwnProperty( value ) ) {
                // Unlikely to be a user error, so don't set message
                result.valid = false;

                console.warn( consoleWarnPrefix + 'Value must be one of: ' + Object.keys( this.options ).join( ', ' ) );
            }
        }

        return result;
    };

    mw.calculators.objectClasses.Variable.prototype.valueUpdated = function() {
        for( var iCalculation in this.calculations ) {
            var calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );

            if( calculation ) {
                calculation.update();
            }
        }
    };



    /**
     * Class AbstractCalculation
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.AbstractCalculation}
     * @constructor
     */
    mw.calculators.objectClasses.AbstractCalculation = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );

        this.initialize();
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );

    mw.calculators.objectClasses.AbstractCalculation.prototype.addCalculation = function( calculationId ) {
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
            return;
        }

        this.calculations.push( calculationId );
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.doRender = function() {
        throw new Error( 'AbstractCalculation child class "' + this.getClassName() + '" must implement doRender()' );
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationData = function() {
        return this.data;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationDataValues = function() {
        var calculationData = this.getCalculationData();

        var missingRequiredData = this.getMissingRequiredData();

        if( missingRequiredData.length ) {
            this.message = missingRequiredData.join( ', ' ) + ' required';

            return false;
        }

        var data = {};

        var calculationId, calculation, variableId, variable;

        var calculations = calculationData.calculations.required.concat( calculationData.calculations.optional );

        for( var iRequiredCalculation in calculations ) {
            calculationId = calculations[ iRequiredCalculation ];
            calculation = mw.calculators.getCalculation( calculationId );

            // We shouldn't use getValue() since that triggers recalculate() which would cause an infinite loop
            data[ calculationId ] = calculation.value;
        }

        var variables = calculationData.variables.required.concat( calculationData.variables.optional );

        for( var iRequiredVariable in variables ) {
            variableId = variables[ iRequiredVariable ];
            variable = mw.calculators.getVariable( variableId );

            data[ variableId ] = variable.getValue();
        }

        return data;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getClassName = function() {
        throw new Error( 'AbstractCalculation child class must implement getClassName()' );
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerClasses = function() {
        return this.getElementClasses();
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerId = function() {
        return this.getElementPrefix() + '-' + this.id;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getDescription = function() {
        return this.description;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getElementPrefix = function( useClassName ) {
        var elementPrefix = 'calculator-';

        elementPrefix += useClassName ? this.getClassName() : 'calculation';

        return elementPrefix;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getElementClasses = function( elementId ) {
        elementId = elementId ? '-' + elementId : '';

        return this.getElementPrefix() + elementId + ' ' +
            this.getElementPrefix( true ) + elementId + ' ' +
            this.getContainerId() + elementId;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getFormula = function() {
        return this.formula;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getInfo = function( infoCount ) {
        var infoHtml = '';

        var description = this.getDescription();

        if( description ) {
            infoHtml += $( '<p>', {
                html: description
            } )[ 0 ].outerHTML;
        }

        var formula = this.getFormula();

        if( formula ) {
            infoHtml += $( '<div>', {
                class: this.getElementClasses( 'formula' )
            } )[ 0 ].outerHTML;
        }

        var references = this.getReferences();

        if( references.length ) {
            var $references = $( '<ol>' );

            for( var iReference in references ) {
                $references.append( $( '<li>', {
                    html: references[ iReference ]
                } ) );
            }

            infoHtml += $( '<div>', {
                class: this.getElementClasses( 'references' )
            } ).append( $references )[ 0 ].outerHTML;
        }

        var infoContainerId = this.getContainerId() + '-info';

        if( infoCount ) {
            infoContainerId += '-' + infoCount;
        }

        $infoContainer = $( '<div>', {
            id: infoContainerId,
            class: 'collapse row no-gutters border-top ' + this.getElementClasses( 'info' )
        } ).append( infoHtml );

        return $infoContainer;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getInfoButton = function( infoCount ) {
        var infoContainerId = this.getContainerId() + '-info';

        if( infoCount ) {
            infoContainerId += '-' + infoCount;
        }

        return $( '<span>', {
            class: this.getElementClasses( 'infoButton' )
        } )
            .append( $( '<a>', {
                'data-toggle': 'collapse',
                href: '#' + infoContainerId,
                role: 'button',
                'aria-expanded': 'false',
                'aria-controls': infoContainerId
            } )
                .append( $( '<i>', {
                    class: 'far fa-question-circle'
                } ) ) );
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getMissingRequiredData = function() {
        var calculationData = this.getCalculationData();

        var missingRequiredData = [];
        var calculation, variable;

        for( var iRequiredCalculation in calculationData.calculations.required ) {
            calculation = mw.calculators.getCalculation( calculationData.calculations.required[ iRequiredCalculation ] );

            if( !calculation.hasValue() ) {
                missingRequiredData = missingRequiredData.concat( calculation.getMissingRequiredData() );
            }
        }

        for( var iRequiredVariable in calculationData.variables.required ) {
            variable = mw.calculators.getVariable( calculationData.variables.required[ iRequiredVariable ] );

            if( !variable.hasValue() ) {
                missingRequiredData.push( String( variable ) );
            }
        }

        return missingRequiredData.filter( mw.calculators.uniqueValues );
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties = function() {
        return {
            required: [
                'id',
                'calculate'
            ],
            optional: [
                'data',
                'description',
                'formula',
                'onRender',
                'onRendered',
                'references',
                'searchData',
                'type'
            ]
        };
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getReferences = function() {
        return this.references;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getSearchString = function() {
        var searchString = this.id;

        searchString += this.searchData ? ' ' + this.searchData : '';

        return searchString.trim();
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getTitleHtml = function() {
        return this.getTitleString();
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getTitleString = function() {
        return this.id;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.getValue = function() {
        // For now, we always need to recalculate, since the calculation may not be rendered but still required by
        // other calculations (i.e. drug dosages using lean body weight).
        this.recalculate();

        return this.value;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.hasInfo = function() {
        return this.getDescription() || this.getFormula() || this.getReferences().length;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.hasValue = function() {
        if( this.value === null ||
            ( this.isValueMathObject() && !this.value.toNumber() ) ) {
            return false;
        }

        return true;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.initialize = function() {
        if( typeof this.calculate !== 'function' ) {
            throw new Error( 'calculate() must be a function for Calculation "' + this.id + '"' );
        }

        // Initialize array to store calculation ids which depend on this calculation's value
        this.calculations = [];

        this.data = new mw.calculators.objectClasses.CalculationData( this.getCalculationData() );

        this.references = this.references ? mw.calculators.prepareReferences( this.references ) : [];

        this.type = this.type ? this.type : TYPE_NUMBER;

        this.message = null;
        this.value = null;

        // Remove any placeholder content explicitly set in the markup (used for SEO).
        $( '.' + this.getContainerId() ).empty();
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.isValueMathObject = function() {
        return mw.calculators.isValueMathObject( this.value );
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.parseFormula = function() {
        var formula = this.getFormula();

        if( !formula ) {
            return;
        }

        var api = new mw.Api();

        var containerId = this.getContainerId() + '-formula';

        api.parse( formula ).then( function( result ) {
            $( '.' + containerId ).html( result );
        } );
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.recalculate = function() {
        this.message = '';
        this.value = null;

        var data = this.getCalculationDataValues();

        if( data === false ) {
            this.valueUpdated();

            return false;
        }

        try {
            var value = this.calculate( data );

            if( this.type === TYPE_NUMBER && !isNaN( value ) ) {
                if( this.units ) {
                    value = value + ' ' + this.units;
                }

                this.value = math.unit( value );
            } else {
                this.value = value;
            }
       } catch( e ) {
            console.warn( e.message );

            this.message = e.message;
            this.value = null;
        } finally {
            this.valueUpdated();
        }

        return true;
    };



    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
        // Need to run rendering in setTimeout to allow browser events to remain responsive
        var calculation = this;

        setTimeout( function() {
            if( typeof calculation.onRender === 'function' ) {
                calculation.onRender();
            }

            calculation.doRender();

            // Send API queries to parse LaTeX formulas
            calculation.parseFormula();

            mw.track( 'mw.calculators.CalculationRendered' );

            if( typeof calculation.onRendered === 'function' ) {
                calculation.onRendered();
            }
        }, 0 );
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.setDependencies = function() {
        this.data = this.getCalculationData();

        var calculationIds = this.data.calculations.required.concat( this.data.calculations.optional );

        for( var iCalculationId in calculationIds ) {
            var calculationId = calculationIds[ iCalculationId ];

            if( !mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
                throw new Error('Calculation "' + calculationId + '" does not exist for calculation "' + this.id + '"');
            }

            mw.calculators.calculations[ calculationId ].addCalculation( this.id );
        }

        var variableIds = this.data.variables.required.concat( this.data.variables.optional );

        for( var iVariableId in variableIds ) {
            var variableId = variableIds[ iVariableId ];

            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                throw new Error('Variable "' + variableId + '" does not exist for calculation "' + this.id + '"');
            }

            mw.calculators.variables[ variableId ].addCalculation( this.id );
        }

        this.recalculate();
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.toString = function() {
        return this.getTitleString();
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.update = function() {
        this.recalculate();

        this.render();
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.valueUpdated = function() {
        for( var iCalculation in this.calculations ) {
            calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );

            if( calculation ) {
                calculation.update();
            }
        }
    };



    /**
     * Class CalculationData
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.CalculationData}
     * @constructor
     */
    mw.calculators.objectClasses.CalculationData = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );

        var dataTypes = this.getDataTypes();
        var dataRequirements = this.getDataRequirements();

        // Iterate through the supported data types (e.g. calculation, variable) to initialize the structure
        for( var iDataType in dataTypes ) {
            var dataType = dataTypes[ iDataType ];

            if( !this[ dataType ] ) {
                this[ dataType ] = {
                    optional: [],
                    required: []
                };
            } else {
                // Iterate through the requirement levels (i.e. optional, required) to initialize the structure
                for( var iDataRequirement in dataRequirements ) {
                    var dataRequirement = dataRequirements[ iDataRequirement ];

                    // FYI can't check to see if the data actually exists here since it may not be defined yet
                    if( !this[ dataType ].hasOwnProperty( dataRequirement ) ) {
                        this[ dataType ][ dataRequirement ] = [];
                    }
                }
            }
        }
    };

    mw.calculators.objectClasses.CalculationData.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );

    mw.calculators.objectClasses.CalculationData.prototype.getDataRequirements = function() {
        return [
            'optional',
            'required'
        ];
    };

    mw.calculators.objectClasses.CalculationData.prototype.getDataTypes = function() {
        return [
            'calculations',
            'variables'
        ];
    };

    mw.calculators.objectClasses.CalculationData.prototype.getProperties = function() {
        return {
            required: [],
            optional: [
                'calculations',
                'variables'
            ]
        };
    };




    mw.calculators.objectClasses.CalculationData.prototype.merge = function() {
        var mergedData = new mw.calculators.objectClasses.CalculationData();

        var data = [ this ].concat( Array.prototype.slice.call( arguments ) );

        var dataTypes = this.getDataTypes();

        for( var iData in data ) {
            for( var iDataType in dataTypes ) {
                var dataType = dataTypes[ iDataType ];

                mergedData[ dataType ].required = mergedData[ dataType ].required
                    .concat( data[ iData ][ dataType ].required )
                    .filter( mw.calculators.uniqueValues );

                mergedData[ dataType ].optional = mergedData[ dataType ].optional
                    .concat( data[ iData ][ dataType ].optional )
                    .filter( mw.calculators.uniqueValues );
            }
        }

        return mergedData;
    };





    /**
     * Class SimpleCalculation
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.SimpleCalculation}
     * @constructor
     */
    mw.calculators.objectClasses.SimpleCalculation = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );

        this.initialize();
    };

    mw.calculators.objectClasses.SimpleCalculation.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculation.prototype );

    mw.calculators.objectClasses.SimpleCalculation.prototype.doRender = function() {
        var $calculationContainer = $( '.' + this.getContainerId() );

        if( !$calculationContainer.length ) {
            return;
        }

        // Add all required classes
        $calculationContainer.addClass( 'row no-gutters border ' + this.getContainerClasses() );

        // Add search phrases
        $calculationContainer.attr( 'data-search', this.getSearchString() );

        // Get a string version of the calculation's value
        var valueString = this.getValueString();

        // We will need to show variable inputs for non-global variable inputs.
        // Global inputs (i.e. those in the header) will claim the DOM id for that variable.
        // Non-global inputs (i.e. specific to a calculation) will only set a class but not the id,
        // and thus will get added to each calculation even if a duplicate.
        // E.g. 2 calculation might use the current hematocrit, but we should show them for both calculations since
        // it wouldn't be obvious the input that only showed the first time would apply to both calculations.
        var inputVariableIds = this.data.variables.required.concat( this.data.variables.optional );
        var missingVariableInputs = [];

        for( var iInputVariableId in inputVariableIds ) {
            var variableId = inputVariableIds[ iInputVariableId ];

            if( !$( '#calculator-input-' + variableId ).length ) {
                missingVariableInputs.push( variableId );
            }
        }

        // Out of 12, uses Bootstrap col- classes in a container
        var titleColumns = '7';
        var valueColumns = '5';

        // Store this object in a local variable since .each() will reassign this to the DOM object of each
        // calculation container.
        var calculation = this;
        var calculationCount = 0;

        // Eventually may implement different rendering, so we should regenerate
        // all elements with each iteration of the loop.
        // I.e. might show result in table and inline in 2 different places of article.
        $calculationContainer.each( function() {
            // Initalize the variables for all the elements of the calculation. These need to be in order of placement
            // in the calculation container
            var elementTypes = [
                'title',
                'variables',
                'value',
                'info'
            ];

            var elements = {};

            for( var iElementType in elementTypes ) {
                var elementType = elementTypes[ iElementType ];

                elements[ elementType ] = {
                    $container: null,
                    id: calculation.getContainerId() + '-' + elementType
                };

                if( calculationCount ) {
                    elements[ elementType ].id += '-' + calculationCount;
                }
            }

            // Create title element and append to container
            elements.title.$container = $( '<div>', {
                id: elements.title.id
            } );

            elements.title.$container.append( calculation.getTitleHtml() );

            if( calculation.hasInfo() ) {
                elements.title.$container.append( calculation.getInfoButton( calculationCount ) );

                // Id of the info container should already be set by getInfo()
                elements.info.$container = calculation.getInfo();
            }

            // Create the value element
            elements.value.$container = $( '<div>' ).append( valueString );

            if( !missingVariableInputs.length ) {
                // If we have no variable inputs to show, we can put the title and value in one row of the table
                elements.title.$container.addClass( 'col-' + titleColumns + ' border-right' );

                // Add the id attribute to the value container
                elements.value.$container.attr( 'id', elements.value.id );

                elements.value.$container.addClass( 'col-' + valueColumns );
            } else {
                // If we need to show variable inputs, make the title span the full width of the container,
                // put the variable inputs on a new row, and show the result on a row below that.
                elements.title.$container.addClass( 'col-12 border-bottom' );
                elements.value.$container.addClass( 'col-12' );

                // Create a new row for the variable inputs
                elements.variables.$container = $( '<div>', {
                    class: 'row no-gutters border-bottom ' + calculation.getElementClasses( 'variables' ),
                    id: elements.variables.id
                } )
                    .append( $( '<div>', {
                        class: 'col-12'
                    } )
                        .append( mw.calculators.createInputGroup( missingVariableInputs ) ) );

                elements.value.$container = $( '<div>', {
                    class: 'row no-gutters',
                    id: elements.value.id
                } )
                    .append(
                        elements.value.$container
                );
            }

            // Add the title classes after the layout classes
            elements.title.$container.addClass( calculation.getElementClasses( 'title' ) );

            elements.value.$container.addClass( calculation.getElementClasses( 'value' ) );

            // Iterate over elementTypes since it is in order of rendering
            for( var iElementType in elementTypes ) {
                var elementType = elementTypes[ iElementType ];

                var $existingContainer = $( '#' + elements[ elementType ].id );

                if( $existingContainer.length ) {
                    // If an input within this container has focus (i.e. the user changed a variable input which
                    // triggered this rerender), don't rerender the element as this would destroy the focus on
                    // the input.
                    if( !$.contains( $existingContainer[ 0 ], $( ':focus' )[ 0 ] ) ) {
                        $existingContainer.replaceWith( elements[ elementType ].$container );
                    }
                } else {
                    $( this ).append( elements[ elementType ].$container );
                }
            }

            calculationCount++;
        } );
    };

    mw.calculators.objectClasses.SimpleCalculation.prototype.getClassName = function() {
        return 'SimpleCalculation';
    };

    mw.calculators.objectClasses.SimpleCalculation.prototype.getProperties = function() {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();

        return this.mergeProperties( inheritedProperties, {
            required: [
                'name'
            ],
            optional: [
                'abbreviation',
                'digits',
                'link',
                'units'
            ]
        } );
    };

    mw.calculators.objectClasses.SimpleCalculation.prototype.getSearchString = function() {
        return ( this.id + ' ' + this.abbreviation + ' ' + this.name + ' ' + this.searchData ).trim();
    };

    mw.calculators.objectClasses.SimpleCalculation.prototype.getTitleHtml = function() {
        var titleHtml = this.getTitleString();

        if( this.link ) {
            var href = this.link;

            // Detect internal links (this isn't great)
            var matches = href.match( /\[\[(.*?)\]\]/ );

            if( matches ) {
                href = mw.util.getUrl( matches[ 1 ] );
            }

            titleHtml = $( '<a>', {
                href: href,
                text: titleHtml
            } )[ 0 ].outerHTML;
        }

        return titleHtml;
    };

    mw.calculators.objectClasses.SimpleCalculation.prototype.getTitleString = function() {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
    };

    mw.calculators.objectClasses.SimpleCalculation.prototype.getValueString = function() {
        if( this.message ) {
            return this.message;
        } else if( typeof this.value === 'object' && this.value.hasOwnProperty( 'value' ) ) {
            return mw.calculators.getValueString( this.value );
        } else {
            return String( this.value );
        }
    };

    mw.calculators.initialize();

}() );