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

From WikiAnesthesia
Line 3: Line 3:
  */
  */
( function() {
( function() {
     var DEFAULT_DRUG_COLOR = 'default';
     var COOKIE_EXPIRATION = 12 * 60 * 60;
    var DEFAULT_DRUG_POPULATION = 'general';
    var DEFAULT_DRUG_ROUTE = 'iv';


     mw.calculators.isValueDependent = function( value, variableId ) {
     var TYPE_NUMBER = 'number';
         // This may need generalized to support other variables in the future
    var TYPE_STRING = 'string';
         if( variableId === 'weight' ) {
 
             return value && value.formatUnits().match( /\/[\s(]*?kg/ );
    var VALID_TYPES = [
        } else {
        TYPE_NUMBER,
            throw new Error( 'Dependence "' + variableId + '" not supported by isValueDependent' );
         TYPE_STRING
    ];
 
    var DEFAULT_CALCULATION_CLASS = 'SimpleCalculation';
    var DEFAULT_CALCULATOR_CLASS = 'SimpleCalculator';
 
    // 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;
     };
     };


    /**
    * Define units
    */
    mw.calculators.addUnitsBases( {
        concentration: {
            toString: function( units ) {
                units = units.replace( ' pct', '%' );
                units = units.replace( 'ug', 'mcg' );


                 return units;
    mw.calculators = {
        calculators: {},
        calculations: {},
        objectClasses: {},
        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();
             }
             }
         },
         },
         mass: {
         addCalculators: function( moduleId, calculatorData, className ) {
             toString: function( units ) {
             className = className ? className : DEFAULT_CALCULATOR_CLASS;
                 units = units.replace( 'ug', 'mcg' );
 
            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 ];


                 return units;
                    if( !mw.calculators.getCalculation( calculationId ) ) {
                        throw new Error( 'Calculator "' + calculatorId + '" references calculation "' + calculationId + '" which is not defined' );
                    }
                 }
             }
             }
        }
    } );


    mw.calculators.addUnits( {
            var calculators = mw.calculators.createCalculatorObjects( className, calculatorData );
        mcg: {
 
             baseName: 'mass',
            // Initalize the calculators property for the module
             definition: '1 ug'
            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();
             }
         },
         },
         pct: {
         addUnitsBases: function( unitsBaseData ) {
             baseName: 'concentration',
             var unitsBases = mw.calculators.createCalculatorObjects( 'UnitsBase', unitsBaseData );
             definition: '10 mg/mL'
 
             for( var unitsBaseId in unitsBases ) {
                mw.calculators.unitsBases[ unitsBaseId ] = unitsBases[ unitsBaseId ];
            }
         },
         },
         vial: {
         addUnits: function( unitsData ) {
             baseName: 'volume'
             var units = mw.calculators.createCalculatorObjects( 'Units', unitsData );
        }
 
    } );
            for( var unitsId in units ) {
                if( mw.calculators.units.hasOwnProperty( unitsId ) ) {
                    continue;
                }


                try {
                    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,
                    };


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


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


    mw.calculators.addDrugColors = function( drugColorData ) {
            for( var variableId in variables ) {
        var drugColors = mw.calculators.createCalculatorObjects( 'DrugColor', drugColorData );
                mw.calculators.variables[ variableId ] = variables[ variableId ];


        for( var drugColorId in drugColors ) {
                var cookieValue = mw.calculators.getCookieValue( variableId );
            mw.calculators.drugColors[ drugColorId ] = drugColors[ drugColorId ];
        }
    };


    mw.calculators.getDrugColor = function( drugColorId ) {
                if( cookieValue ) {
        if( mw.calculators.drugColors.hasOwnProperty( drugColorId ) ) {
                    try {
            return mw.calculators.drugColors[ drugColorId ];
                        // isValueValid will throw an error if invalid, so the catch clause is our else condition
        } else {
                        if( mw.calculators.variables[ variableId ].isValueValid( cookieValue ) ) {
            return null;
                            mw.calculators.variables[ variableId ].setValue( cookieValue );
         }
                        }
    };
                    } catch( e ) {
                        // 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 = {};
    * Class DrugColor
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.DrugColor}
    * @constructor
    */
    mw.calculators.objectClasses.DrugColor = function( propertyValues ) {
        var properties = {
            required: [
                'id'
            ],
            optional: [
                'parentColor',
                'primaryColor',
                'highlightColor',
                'striped'
            ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
            for( var objectId in objectData ) {
                var propertyValues = objectData[ objectId ];


        this.parentColor = this.parentColor || this.id === DEFAULT_DRUG_COLOR ? this.parentColor : DEFAULT_DRUG_COLOR;
                // 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;
                }


    mw.calculators.objectClasses.DrugColor.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                objects[ objectId ] = new mw.calculators.objectClasses[ className ]( propertyValues );
            }


    mw.calculators.objectClasses.DrugColor.prototype.getParentDrugColor = function() {
            return objects;
        if( !this.parentColor ) {
        },
            return null;
        createInputGroup: function( variableIds ) {
        }
            var $form = $( '<form>', {


        var parentDrugColor = mw.calculators.getDrugColor( this.parentColor );
            } );


        if( !parentDrugColor ) {
            var $formRow = $( '<div>', {
            throw new Error( 'Parent drug color "' + this.parentColor + '" not found for drug color "' + this.id + '"' );
                class: 'form-row'
        }
            } ).css( 'flex-wrap', 'nowrap' );


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


    mw.calculators.objectClasses.DrugColor.prototype.getHighlightColor = function() {
                if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
        if( this.highlightColor ) {
                    throw new Error( 'Invalid variable name "' + variableId + '"' );
            return this.highlightColor;
                }
        } else if( this.parentColor ) {
            return this.getParentDrugColor().getHighlightColor();
        }
    };


    mw.calculators.objectClasses.DrugColor.prototype.getPrimaryColor = function() {
                $formRow.append( mw.calculators.variables[ variableId ].createInput() );
        if( this.primaryColor ) {
             }
            return this.primaryColor;
        } else if( this.parentColor ) {
             return this.getParentDrugColor().getPrimaryColor();
        }
    };


    mw.calculators.objectClasses.DrugColor.prototype.isStriped = function() {
            return $form.append( $formRow );
         if( this.striped !== null ) {
        },
             return this.striped;
         getCookieKey: function( variableId ) {
         } else if( this.parentColor ) {
             return 'calculators-var-' + variableId;
             return this.getParentDrugColor().isStriped();
         },
        }
        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;
            }
        },
        getCalculator: function( moduleId, calculatorId ) {
            if( mw.calculators.calculators.hasOwnProperty( moduleId ) &&
                mw.calculators.calculators[ moduleId ].hasOwnProperty( calculatorId ) ) {
                return mw.calculators.calculators[ moduleId ][ calculatorId ];
            } else {
                return null;
            }
        },
        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 ];


    /**
                unitsByBase[ units.unit.base.key.toLowerCase() ] = units.prefix.name + units.unit.name;
    * DrugPopulation
            }
    */


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


    mw.calculators.addDrugPopulations = function( drugPopulationData ) {
            var unitsString = value.formatUnits();
        var drugPopulations = mw.calculators.createCalculatorObjects( 'DrugPopulation', drugPopulationData );


        for( var drugPopulationId in drugPopulations ) {
            var reDenominator = /\/\s?\((.*)\)/;
             mw.calculators.drugPopulations[ drugPopulationId ] = drugPopulations[ drugPopulationId ];
             var denominatorMatches = unitsString.match( reDenominator );
        }
    };


    mw.calculators.getDrugPopulation = function( drugPopulationId ) {
            if( denominatorMatches ) {
        if( mw.calculators.drugPopulations.hasOwnProperty( drugPopulationId ) ) {
                var denominatorUnits = denominatorMatches[ 1 ];
            return mw.calculators.drugPopulations[ drugPopulationId ];
        } else {
            return null;
        }
    };


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


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


    /**
            var unitsBase = value.getBase();
    * Class DrugPopulation
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.DrugPopulation}
    * @constructor
    */
    mw.calculators.objectClasses.DrugPopulation = function( propertyValues ) {
        var properties = {
            required: [
                'id',
                'name'
            ],
            optional: [
                'abbreviation',
                'variables'
            ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
            if( unitsBase ) {
                unitsBase = unitsBase.toLowerCase();


        if( this.variables ) {
                if( mw.calculators.unitsBases.hasOwnProperty( unitsBase ) &&
            for( var variableId in this.variables ) {
                    typeof mw.calculators.unitsBases[ unitsBase ].toString === 'function' ) {
                if( !mw.calculators.getVariable( variableId ) ) {
                     unitsString = mw.calculators.unitsBases[ unitsBase ].toString( unitsString );
                     throw new Error( 'DrugPopulation variable "' + variableId + '" not defined' );
                 }
                 }
            } 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' );
            }


                this.variables[ variableId ].min = this.variables[ variableId ].hasOwnProperty( 'min' ) ?
            return unitsString;
                    math.unit( this.variables[ variableId ].min ) : null;
        },
        getValueDecimals: function( value ) {
            // Supports either numeric values or math objects
            if( mw.calculators.isValueMathObject( value ) ) {
                value = mw.calculators.getValueNumber( value );
            }


                this.variables[ variableId ].max = this.variables[ variableId ].hasOwnProperty( 'max' ) ?
            if( typeof value !== 'number' ) {
                    math.unit( this.variables[ variableId ].max ) : null;
                return null;
             }
             }
        } else {
            this.variables = {};
        }
    };


    mw.calculators.objectClasses.DrugPopulation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
            // 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( '.' );


    mw.calculators.objectClasses.DrugPopulation.prototype.getCalculationData = function() {
            // If no decimal is present, will be set to -1 by indexOf. If so, set to 0.
        var inputData = new mw.calculators.objectClasses.CalculationData();
            decimals = decimals > 0 ? decimals : 0;


         for( var variableId in this.variables ) {
            return decimals;
             inputData.variables.required.push( variableId );
         },
        }
        getValueNumber: function( value, decimals ) {
             if( typeof value !== 'object' ) {
                return null;
            }


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


    mw.calculators.objectClasses.DrugPopulation.prototype.getCalculationDataScore = function( dataValues ) {
            var absNumber = math.abs( number );
        // A return value of -1 indicates the data did not match the population definition


        for( var variableId in this.variables ) {
            if( absNumber >= 10 ) {
             if( !dataValues.hasOwnProperty( variableId ) ) {
                decimals = 0;
                return -1;
             } else {
                decimals = -math.floor( math.log10( absNumber ) ) + 1;
             }
             }


             if( this.variables[ variableId ].min &&
             return math.round( number, decimals );
                ( !dataValues[ variableId ] ||
        },
                    !math.largerEq( dataValues[ variableId ], this.variables[ variableId ].min ) ) ) {
        getValueString: function( value, decimals ) {
                 return -1;
            if( !mw.calculators.isValueMathObject( value ) ) {
                 return null;
             }
             }


             if( this.variables[ variableId ].max &&
            var valueNumber = mw.calculators.getValueNumber( value, decimals );
                 ( !dataValues[ variableId ] ||
            var valueUnits = mw.calculators.getUnitsString( value );
                     !math.smallerEq( dataValues[ variableId ], this.variables[ variableId ].max ) ) ) {
 
                 return -1;
             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 ) {
                        var newValue = math.unit( newSIValue.toNumber() + ' ' + value.formatUnits().replace( oldSIUnit, newSIUnit ) );
 
                        valueNumber = mw.calculators.getValueNumber( newValue, decimals );
                        valueUnits = mw.calculators.getUnitsString( newValue );
                    }
                 }
             }
             }
        }


        // If the data matches the population definition, the score corresponds to the number of variables in the
            var valueString = String( valueNumber );
        // population definition. This should roughly correspond to the specificity of the population.
        return Object.keys( this.variables ).length;
    };


    mw.calculators.objectClasses.DrugPopulation.prototype.toString = function() {
            if( valueUnits ) {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
                valueString += ' ' + valueUnits;
    };
            }


            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() {
            $( '.calculator' ).each( function() {
                var gadgetModule = 'ext.gadget.calculator-' + $( this ).attr( 'data-module' );


                if( gadgetModule && mw.loader.getState( gadgetModule ) === 'registered' ) {
                    mw.loader.load( gadgetModule );
                }
            } );
        },
        isMobile: function() {
            return window.matchMedia( 'only screen and (max-width: 760px)' ).matches;
        },
        isValueMathObject: function( value ) {
            return value && value.hasOwnProperty( 'value' );
        },
        setCookieValue: function( variableId, value ) {
            mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
                expires: COOKIE_EXPIRATION
            } );
        },
        setValue: function( variableId, value ) {
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return false;
            }


    /**
            if( mw.calculators.variables[ variableId ].setValue( value ) ) {
    * DrugRoute
                mw.calculators.setCookieValue( variableId, value );
    */
    mw.calculators.drugRoutes = {};


    mw.calculators.addDrugRoutes = function( drugRouteData ) {
                return true;
        var drugRoutes = mw.calculators.createCalculatorObjects( 'DrugRoute', drugRouteData );
            }


        for( var drugRouteId in drugRoutes ) {
             return false;
             mw.calculators.drugRoutes[ drugRouteId ] = drugRoutes[ drugRouteId ];
         },
         }
        uniqueValues: function( value, index, self ) {
    };
            return self.indexOf( value ) === index;
 
    mw.calculators.getDrugRoute = function( drugRouteId ) {
        if( mw.calculators.drugRoutes.hasOwnProperty( drugRouteId ) ) {
            return mw.calculators.drugRoutes[ drugRouteId ];
        } else {
            return null;
         }
         }
     };
     };


     /**
     /**
     * Class DrugRoute
     * Class CalculatorObject
    *
    * @param {Object} properties
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.DrugRoute}
     * @returns {mw.calculators.objectClasses.CalculatorObject}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.DrugRoute = function( propertyValues ) {
     mw.calculators.objectClasses.CalculatorObject = function( properties, propertyValues ) {
         var properties = {
         propertyValues = propertyValues ? propertyValues : {};
             required: [
 
                'id',
        if( properties ) {
                 'name'
             if( properties.hasOwnProperty( 'required' ) ) {
            ],
                 for( var iRequiredProperty in properties.required ) {
            optional: [
                    var requiredProperty = properties.required[ iRequiredProperty ];
                'abbreviation',
 
                'default'
                    if( !propertyValues || !propertyValues.hasOwnProperty( requiredProperty ) ) {
            ]
                        console.error( 'Missing required property "' + requiredProperty + '"' );
        };
                        console.log( propertyValues );


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


    mw.calculators.objectClasses.DrugRoute.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                    this[ requiredProperty ] = propertyValues[ requiredProperty ];


    mw.calculators.objectClasses.DrugRoute.prototype.toString = function() {
                    delete propertyValues[ requiredProperty ];
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
                }
    };
            }


            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 ) {
    * DrugIndication
        var uniqueValues = function( value, index, self ) {
    */
            return self.indexOf( value ) === index;
     mw.calculators.drugIndications = {};
        };


    mw.calculators.addDrugIndications = function( drugIndicationData ) {
        properties.required = inheritedProperties.required.concat( properties.required ).filter( uniqueValues );
         var drugIndications = mw.calculators.createCalculatorObjects( 'DrugIndication', drugIndicationData );
         properties.optional = inheritedProperties.optional.concat( properties.optional ).filter( uniqueValues );


         for( var drugIndicationId in drugIndications ) {
         return properties;
            mw.calculators.drugIndications[ drugIndicationId ] = drugIndications[ drugIndicationId ];
        }
     };
     };


    mw.calculators.getDrugIndication = function( drugIndicationId ) {
 
        if( mw.calculators.drugIndications.hasOwnProperty( drugIndicationId ) ) {
 
            return mw.calculators.drugIndications[ drugIndicationId ];
        } else {
            return null;
        }
    };


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


     mw.calculators.objectClasses.DrugIndication.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
     mw.calculators.objectClasses.UnitsBase.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
 
    mw.calculators.objectClasses.DrugIndication.prototype.toString = function() {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
    };
 




Line 354: Line 484:


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


    mw.calculators.addDrugs = function( drugData ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
         var drugs = mw.calculators.createCalculatorObjects( 'Drug', drugData );
 
        for( var drugId in drugs ) {
            mw.calculators.drugs[ drugId ] = drugs[ drugId ];
 
            var drugDosageCalculationId = mw.calculators.getDrugDosageCalculationId( drugId );
            var drugDosageCalculation = mw.calculators.getCalculation( drugDosageCalculationId );
 
            if( !drugDosageCalculation ) {
                var calculationData = {};
 
                calculationData[ drugDosageCalculationId ] = {
                    calculate: mw.calculators.objectClasses.DrugDosageCalculation.prototype.calculate,
                    drug: drugId,
                    type: 'drug'
                };
 
                mw.calculators.addCalculations( calculationData, 'DrugDosageCalculation' );
 
                drugDosageCalculation = mw.calculators.getCalculation( drugDosageCalculationId );
            }
 
            drugDosageCalculation.setDependencies();
        }
     };
     };


     mw.calculators.addDrugDosages = function( drugId, drugDosageData ) {
     mw.calculators.objectClasses.Units.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        var drug = mw.calculators.getDrug( drugId );


        if( !drug ) {
            throw new Error( 'DrugDosage references drug "' + drugId + '" which is not defined' );
        }
        drug.addDosages( drugDosageData );
        // Update calculation dependencies
        var drugDosageCalculation = mw.calculators.getCalculation( mw.calculators.getDrugDosageCalculationId( drugId ) );
        drugDosageCalculation.updateVariables();
        drugDosageCalculation.setDependencies();
    };
    mw.calculators.getDrug = function( drugId ) {
        if( mw.calculators.drugs.hasOwnProperty( drugId ) ) {
            return mw.calculators.drugs[ drugId ];
        } else {
            return null;
        }
    };






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


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


         var color = mw.calculators.getDrugColor( this.color );
         // 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 = {};


        if( !color ) {
            for( var iOption in this.options ) {
            throw new Error( 'Invalid drug color "' + this.color + '" for drug "' + this.id + '"' );
                var option = this.options[ iOption ];
        }


        this.color = color;
                options[ option ] = option;
            }


        if( this.preparations ) {
            this.options = options;
            var preparationData = this.preparations;
        }


            this.preparations = [];
        this.calculations = [];


            this.addPreparations( preparationData );
        if( this.defaultValue ) {
        } else {
             this.defaultValue = this.prepareValue( this.defaultValue );
             this.preparations = [];
         }
         }


         if( this.dosages ) {
         this.value = null;
            var dosageData = this.dosages;
    };


            this.dosages = [];
    mw.calculators.objectClasses.Variable.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );


            this.addDosages( dosageData );
    mw.calculators.objectClasses.Variable.prototype.addCalculation = function( calculationId ) {
         } else {
         if( this.calculations.indexOf( calculationId ) !== -1 ) {
             this.dosages = [];
             return;
         }
         }
        this.calculations.push( calculationId );
     };
     };


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


    mw.calculators.objectClasses.Drug.prototype.addDosages = function( dosageData ) {
        inputOptions.class = inputOptions.hasOwnProperty( 'class' ) ? inputOptions.class : '';
         var dosages = mw.calculators.createCalculatorObjects( 'DrugDosage', dosageData );
        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 : '';


         for( var dosageId in dosages ) {
         var variableId = this.id;
            dosages[ dosageId ].id = this.dosages.length;
        var inputId = 'calculator-input-' + variableId;


            this.dosages.push( dosages[ dosageId ] );
        var inputContainerTag = inputOptions.inline ? '<span>' : '<div>';
        }
    };


    mw.calculators.objectClasses.Drug.prototype.addPreparations = function( preparationData ) {
        var inputContainerAttributes = {
        var preparations = mw.calculators.createCalculatorObjects( 'DrugPreparation', preparationData );
            class: 'form-group mb-0 calculator-container-input'
        };


         for( var preparationId in preparations ) {
         inputContainerAttributes.class += inputOptions.class ? ' ' + inputOptions.class : '';
            preparations[ preparationId ].id = this.preparations.length;
        inputContainerAttributes.class += ' calculator-container-input-' + variableId;


            this.preparations.push( preparations[ preparationId ] );
         var inputContainerCss = {};
         }
    };


    mw.calculators.objectClasses.Drug.prototype.getIndications = function() {
        // Initialize label attributes
         var indications = [];
        var labelAttributes = {
            for: inputId,
            html: this.getLabelString()
         };


         for( var iDosage in this.dosages ) {
         if( inputOptions.hideLabel || ( inputOptions.hideLabelMobile && mw.calculators.isMobile() ) ) {
            if( this.dosages[ iDosage ].indication ) {
            labelAttributes.class = 'sr-only';
                indications.push( this.dosages[ iDosage ].indication );
            }
         }
         }


         return indications.filter( mw.calculators.uniqueValues );
         var labelCss = {};
    };
 
    mw.calculators.objectClasses.Drug.prototype.getPopulations = function( indicationId ) {
        var populations = [];
 
        for( var iDosage in this.dosages ) {
            if( this.dosages[ iDosage ].population &&
                ( !indicationId || ( this.dosages[ iDosage ].indication && this.dosages[ iDosage ].indication.id === indicationId ) ) ) {
                populations.push( this.dosages[ iDosage ].population );
            }
        }


         return populations.filter( mw.calculators.uniqueValues );
         if( inputOptions.inline ) {
    };
            inputContainerTag = '<span>';


    mw.calculators.objectClasses.Drug.prototype.getRoutes = function( indicationId ) {
            inputContainerCss[ 'align-items' ] = 'center';
        var routes = [];
            inputContainerCss[ 'display' ] = 'flex';
            //inputContainerCss[ 'height' ] = 'calc(1.5em + 0.75rem + 2px)';


        for( var iDosage in this.dosages ) {
             labelAttributes.html += ':&nbsp;';
             if( this.dosages[ iDosage ].route &&
            labelCss[ 'margin-bottom' ] = 0;
                ( !indicationId || ( this.dosages[ iDosage ].indication && this.dosages[ iDosage ].indication.id === indicationId ) ) ) {
                routes.push( this.dosages[ iDosage ].route );
            }
         }
         }


         return routes.filter( mw.calculators.uniqueValues );
         // Create the input container
    };
        var $inputContainer = $( inputContainerTag, inputContainerAttributes ).css( inputContainerCss );


    mw.calculators.objectClasses.Drug.prototype.getPreparations = function( excludeDilutionRequired ) {
        var $label = $( '<label>', labelAttributes ).css( labelCss );
        var preparations = this.preparations.filter( mw.calculators.uniqueValues );


         if( excludeDilutionRequired ) {
         $inputContainer.append( $label );
            for( var iPreparation in preparations ) {
                if( preparations[ iPreparation ].dilutionRequired ) {
                    delete preparations[ iPreparation ];
                }
            }
        }


         return preparations;
         var value = this.getValue();
    };


    mw.calculators.objectClasses.Drug.prototype.getProperties = function() {
        if( this.type === TYPE_NUMBER ) {
        return {
             // Initialize the primary units variables (needed for handlers, even if doesn't have units)
             required: [
             var unitsId = null;
                'id',
             var $unitsContainer = null;
                'name'
             ],
             optional: [
                'color',
                'dosages',
                'preparations'
            ]
        };
    };


            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
    * DrugPreparation
            if( this.maxLength ) {
    */
                inputAttributes.maxlength = this.maxLength;
    mw.calculators.addDrugPreparations = function( drugId, drugPreparationData ) {
            }
        var drug = mw.calculators.getDrug( drugId );


        if( !drug ) {
            // Add any additional classes to the input
             throw new Error( 'DrugPreparation references drug "' + drugId + '" which is not defined' );
             inputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
        }


        drug.addPreparations( drugPreparationData );
            // Add the input id to the list of classes
            inputAttributes.class += ' ' + inputId;


        var drugDosageCalculation = mw.calculators.getCalculation( mw.calculators.getDrugDosageCalculationId( drugId ) );
            // If the variable has units, create the units input
            if( this.hasUnits() ) {
                // Set the units id
                unitsId = inputId + '-units';


        drugDosageCalculation.recalculate();
                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 ) {
    * Class DrugPreparation
                    unitsInputAttributes.type = 'hidden';
    * @param {Object} propertyValues
                    unitsInputAttributes.value = this.units[ 0 ];
    * @returns {mw.calculators.objectClasses.DrugPreparation}
    * @constructor
    */
    mw.calculators.objectClasses.DrugPreparation = function( propertyValues ) {
        var properties = {
            required: [
                'id',
                'concentration'
            ],
            optional: [
                'default',
                'dilutionRequired',
                'commonDilution'
            ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
                    $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 : '';


        this.concentration = this.concentration.replace( 'mcg', 'ug' );
                    unitsInputAttributes.class = unitsInputAttributes.class + ' ' + unitsId;


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


    mw.calculators.objectClasses.DrugPreparation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                            var newValue = numberValue ? numberValue + ' ' + $( this ).val() : null;


    mw.calculators.objectClasses.DrugPreparation.prototype.getVolumeUnits = function() {
                            mw.calculators.setValue( variableId, newValue );
        // The units of concentration will always be of the form "mass / volume"
                        } );
        // The regular expression matches all text leading up to the volume units
        return mw.calculators.getUnitsByBase( this.concentration ).volume;
    };


    mw.calculators.objectClasses.DrugPreparation.prototype.toString = function() {
                    for( var iUnits in this.units ) {
        return mw.calculators.getValueString( this.concentration );
                        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
    * Class DrugDosage
            var $input = $( '<input>', inputAttributes )
    * @param {Object} propertyValues
                .on( 'input', function() {
    * @returns {mw.calculators.objectClasses.DrugDosage}
                    var numberValue = $( this ).val();
    * @constructor
    */
    mw.calculators.objectClasses.DrugDosage = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


        var drugIndication = mw.calculators.getDrugIndication( this.indication );
                    var newValue = numberValue ? numberValue : null;


        if( !drugIndication ) {
                    if( newValue && unitsId ) {
            throw new Error( 'Invalid indication "' + this.indication + '" for drug dosage' );
                        newValue = newValue + ' ' + $( '#' + unitsId ).val();
        }
                    }


        this.indication = drugIndication;
                    mw.calculators.setValue( variableId, newValue );
                } );


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


        var drugPopulation = mw.calculators.getDrugPopulation( this.population );
            if( $unitsContainer ) {
                $inputGroup.append( $unitsContainer );
            }


         if( !drugPopulation ) {
            $inputContainer.append( $inputGroup );
             throw new Error( 'Invalid population "' + this.population + '" for drug dosage' );
         } else if( this.type === TYPE_STRING ) {
        }
             if( this.hasOptions() ) {
                var optionKeys = Object.keys( this.options );


        this.population = drugPopulation;
                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'
                    };


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


        var drugRoute = mw.calculators.getDrugRoute( this.route );
                    var $select = $( '<select>', selectAttributes )
                        .on( 'change', function() {
                            mw.calculators.setValue( variableId, $( this ).val() );
                        } );


        if( !drugRoute ) {
                    for( var optionId in this.options ) {
            throw new Error( 'Invalid route "' + this.route + '" for drug dosage' );
                        var displayText = this.options[ optionId ];
        }


        this.route = drugRoute;
                        var optionAttributes = {
                            value: optionId,
                            text: displayText
                        };


        // Add the dose objects to the drug
                        if( optionId === value ) {
        var drugDoseData = this.dose;
                            optionAttributes.selected = true;
        this.dose = [];
                        }


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


    mw.calculators.objectClasses.DrugDosage.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                    $inputContainer.append( $select );
 
                }
    mw.calculators.objectClasses.DrugDosage.prototype.addDoses = function( drugDoseData ) {
             }
        // Each dosage can have one or more associated doses. Ensure this value is an array.
        if( !Array.isArray( drugDoseData ) ) {
             drugDoseData = [ drugDoseData ];
         }
         }


         var doses = mw.calculators.createCalculatorObjects( 'DrugDose', drugDoseData );
         return $inputContainer;
 
        for( var doseId in doses ) {
            doses[ doseId ].id = this.dose.length;
 
            this.dose.push( doses[ doseId ] );
        }
     };
     };


     mw.calculators.objectClasses.DrugDosage.prototype.getCalculationData = function() {
     mw.calculators.objectClasses.Variable.prototype.getLabelString = function() {
         var inputData = new mw.calculators.objectClasses.CalculationData();
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
 
        inputData = inputData.merge( this.population.getCalculationData() );
 
        for( var iDose in this.dose ) {
            inputData = inputData.merge( this.dose[ iDose ].getCalculationData() );
        }
 
        return inputData;
     };
     };


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


     mw.calculators.objectClasses.DrugDosage.prototype.hasInfo = function() {
     mw.calculators.objectClasses.Variable.prototype.getValue = function() {
         return this.description;
         if( this.value !== null ) {
            return this.value;
        } else if( 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 ||
    * Class DrugDose
            ( mw.calculators.isValueMathObject( value ) && !value.toNumber() ) ) {
    * @param {Object} propertyValues
            return false;
    * @returns {mw.calculators.objectClasses.DrugDose}
        }
    * @constructor
 
    */
        return true;
     mw.calculators.objectClasses.DrugDose = function( propertyValues ) {
     };
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


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


            // weightCalculation property will contain references to the actual objects, so reinitialize
    mw.calculators.objectClasses.Variable.prototype.isValueValid = function( value ) {
             this.weightCalculation = [];
        if( value === null ) {
             return true;
        }


             if( !Array.isArray( weightCalculationIds ) ) {
        if( this.type === TYPE_NUMBER ) {
                 weightCalculationIds = [ weightCalculationIds ];
             if( typeof value !== 'object' ) {
                 value = math.unit( value );
             }
             }


             for( var iWeightCalculation in weightCalculationIds ) {
             if( this.hasUnits() ) {
                 var weightCalculationId = weightCalculationIds[ iWeightCalculation ];
                 var valueUnits = value.formatUnits();
                var weightCalculation = mw.calculators.getCalculation( weightCalculationId );


                 if( !weightCalculation ) {
                 if( !valueUnits ) {
                     throw new Error( 'Drug dose references weight calculation "' + weightCalculationId + '" which is not defined' );
                     throw new Error( 'Could not set value for "' + this.id + '": Value must define units' );
                } else if( this.units.indexOf( valueUnits ) === -1 ) {
                    throw new Error( 'Could not set value for "' + this.id + '": Units "' + valueUnits + '" are not valid for this variable' );
                 }
                 }
                this.weightCalculation.push( weightCalculation );
             }
             }
         } else {
         } else if( this.hasOptions() ) {
             this.weightCalculation = [];
             if( !this.options.hasOwnProperty( value ) ) {
                throw new Error( 'Could not set value "' + value + '" for "' + this.id + '": Value must define be one of: ' + Object.keys( this.options ).join( ', ' ) );
            }
         }
         }


         var mathProperties = this.getMathProperties();
         return true;
        var isWeightDependent = false;
    };


         for( var iMathProperty in mathProperties ) {
    mw.calculators.objectClasses.Variable.prototype.prepareValue = function( value ) {
             var mathProperty = mathProperties[ iMathProperty ];
         if( !this.isValueValid( value ) ) {
             // isValueValid will throw a meaningful error to the console
            return null;
        }


            if( this[ mathProperty ] ) {
        if( value !== null ) {
                // TODO consider making a UnitsBase.weight.fromString()
            if( this.type === TYPE_NUMBER ) {
                this[ mathProperty ] = this[ mathProperty ].replace( 'kg', 'kgwt' );
                 if( typeof value !== 'object' ) {
                 this[ mathProperty ] = this[ mathProperty ].replace( 'mcg', 'ug' );
                    value = math.unit( value );
 
                this[ mathProperty ] = math.unit( this[ mathProperty ] );
 
                if( mw.calculators.isValueDependent( this[ mathProperty ], 'weight' ) ) {
                    isWeightDependent = true;
                 }
                 }
            } else {
                this[ mathProperty ] = null;
             }
             }
         }
         }


         if( isWeightDependent ) {
         return value;
            // Default is tbw
            this.weightCalculation.push( mw.calculators.getCalculation( 'tbw' ) );
        }
     };
     };


     mw.calculators.objectClasses.DrugDose.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
     mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
        this.value = this.prepareValue( value );


    mw.calculators.objectClasses.DrugDose.prototype.getAdministration = function() {
        this.valueUpdated();
        var administration = '';


         if( this.frequency ) {
         return true;
             administration += administration ? ' ' : '';
    };
             administration += this.frequency;
 
    mw.calculators.objectClasses.Variable.prototype.valueUpdated = function() {
        for( var iCalculation in this.calculations ) {
             var calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );
 
             if( calculation ) {
                calculation.render();
            }
         }
         }
    }


        if( this.duration ) {
            administration += administration ? ' ' : '';
            administration += 'over ' + this.duration;
        }


         return administration;
    /**
    * 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.DrugDose.prototype.getCalculationData = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        var calculationData = new mw.calculators.objectClasses.CalculationData();


        for( var iWeightCalculation in this.weightCalculation ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.addCalculation = function( calculationId ) {
            calculationData.calculations.optional.push( this.weightCalculation[ iWeightCalculation ].id );
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
            return;
         }
         }


         return calculationData;
        this.calculations.push( calculationId );
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.doRender = function() {};
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerClass = function() {
         return 'calculator-calculation-' + this.id;
     };
     };


     mw.calculators.objectClasses.DrugDose.prototype.getMathProperties = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getLabelString = function() {
         return [
         return this.id;
            'dose',
            'min',
            'max',
            'absoluteMax'
        ];
     };
     };


     mw.calculators.objectClasses.DrugDose.prototype.getProperties = function() {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties = function() {
         return {
         return {
             required: [
             required: [
                 'id'
                 'id',
                'calculate'
             ],
             ],
             optional: [
             optional: [
                 'absoluteMax',
                 'data',
                 'dose',
                 'description',
                 'duration',
                 'onRender',
                 'frequency',
                 'onRendered',
                 'min',
                 'references',
                 'max',
                 'type'
                'name',
                'weightCalculation'
             ]
             ]
         };
         };
     };
     };


    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() {
     mw.calculators.getDrugDosageCalculationId = function( drugId ) {
         return false;
         return 'drugDosages-' + drugId;
     };
     };


     /**
     mw.calculators.objectClasses.AbstractCalculation.prototype.hasValue = function() {
    * Class DrugDosageCalculation
         if( this.value === null ||
    * @param {Object} propertyValues
            ( this.isValueMathObject() && !this.value.toNumber() ) ) {
    * @returns {mw.calculators.objectClasses.DrugDosageCalculation}
            return false;
    * @constructor
        }
    */
    mw.calculators.objectClasses.DrugDosageCalculation = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


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


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


     mw.calculators.objectClasses.DrugDosageCalculation.prototype.calculate = function( data ) {
     mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationDataValues = function() {
         var value = {
         var calculationData = this.getCalculationData();
            dosageId: null,
            message: null,
            population: null,
            preparation: data.preparation,
            dose: []
        };


         if( !data.drug.dosages.length ) {
         var data = {};
            value.message = 'No dose data';
        var missingRequiredData = '';
        var calculationId, calculation, variableId, variable;


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


        // Determine which dosage to use
            if( !calculation ) {
        var populationScores = [];
                throw new Error( 'Invalid required calculation "' + calculationId + '" for calculation "' + this.id + '"' );
            } else if( !calculation.hasValue() ) {
                if( missingRequiredData ) {
                    missingRequiredData = missingRequiredData + ', ';
                }


        for( var iDosage in data.drug.dosages ) {
                missingRequiredData = missingRequiredData + calculation.getLabelString();
            var drugDosage = data.drug.dosages[ iDosage ];
             } else {
 
                 data[ calculationId ] = calculation.value;
             // If the indication and route do not match, set the score to -1
             }
            var populationScore =
                 drugDosage.indication.id === data.indication.id && drugDosage.route.id === data.route.id ?
                drugDosage.population.getCalculationDataScore( data ) : -1;
 
             populationScores.push( populationScore );
         }
         }


         var maxPopulationScore = Math.max.apply( null, populationScores );
         for( var iRequiredVariable in calculationData.variables.required ) {
            variableId = calculationData.variables.required[ iRequiredVariable ];
            variable = mw.calculators.getVariable( variableId );


        if( maxPopulationScore < 0 ) {
            if( !variable ) {
            value.message = 'No dose data for indication "' + String( data.indication ) + '" and route "' + String( data.route ) + '"';
                throw new Error( 'Invalid required variable "' + variableId + '" for calculation "' + this.id + '"' );
            } else if( !variable.hasValue() ) {
                if( missingRequiredData ) {
                    missingRequiredData = missingRequiredData + ', ';
                }


             return value;
                missingRequiredData = missingRequiredData + variable.getLabelString();
             } else {
                data[ variableId ] = variable.getValue();
            }
         }
         }


         // If there is more than one dosage with the same score, take the first.
         if( missingRequiredData ) {
        // This allows the data editor to decide which is most important.
            this.message = missingRequiredData + ' required';
        value.dosageId = populationScores.indexOf( maxPopulationScore );


        var dosage = data.drug.dosages[ value.dosageId ];
            return false;
 
         }
         // A dosage may contain multiple doses (e.g. induction and maintenance)
        for( var iDose in dosage.dose ) {
            var dose = dosage.dose[ iDose ];
            var mathProperties = dose.getMathProperties();
 
            var weightCalculation = null;
            var weightValue = null;


            // data.weightCalculation should be in order of preference, so take the first non-null value
        for( var iOptionalCalculation in calculationData.calculations.optional ) {
            for( var iWeightCalculation in dose.weightCalculation ) {
            calculationId = calculationData.calculations.optional[ iOptionalCalculation ];
                if( dose.weightCalculation[ iWeightCalculation ].value !== null ) {
            calculation = mw.calculators.getCalculation( calculationId );
                    weightCalculation = dose.weightCalculation[ iWeightCalculation ];
                    weightValue = dose.weightCalculation[ iWeightCalculation ].value;


                    break;
            if( !calculation ) {
                 }
                 throw new Error( 'Invalid optional calculation "' + calculationId + '" for calculation "' + this.id + '"' );
             }
             }


             // Initialize value properties for dose
             data[ calculationId ] = calculation.hasValue() ? calculation.value : null;
            value.dose[ iDose ] = {
        }
                massPerWeight: {},
                mass: {},
                volume: {},
                weightCalculation: weightCalculation ? weightCalculation : null
            };


             var massUnits;
        for( var iOptionalVariable in calculationData.variables.optional ) {
             var volumeUnits;
             variableId = calculationData.variables.optional[ iOptionalVariable ];
             variable = mw.calculators.getVariable( variableId );


             for( var iMathProperty in mathProperties ) {
             if( !variable ) {
                 var mathProperty = mathProperties[ iMathProperty ];
                 throw new Error( 'Invalid optional variable "' + variableId + '" for calculation "' + this.id + '"' );
            }


                var doseValue = dose[ mathProperty ];
            data[ variableId ] = variable.hasValue() ? variable.getValue() : null;
        }


                if( doseValue ) {
        return data;
                    var doseUnitsByBase = mw.calculators.getUnitsByBase( doseValue );
    };


                    if( doseUnitsByBase.hasOwnProperty( 'weight' ) ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.initialize = function() {
                        value.dose[ iDose ].massPerWeight[ mathProperty ] = doseValue;
        if( typeof this.calculate !== 'function' ) {
            throw new Error( 'calculate() must be a function for Calculation "' + this.id + '"' );
        }


                        if( weightValue ) {
        // Initialize array to store calculation ids which depend on this calculation's value
                            massUnits = doseUnitsByBase.mass;
        this.calculations = [];


                            if( doseUnitsByBase.hasOwnProperty( 'time' ) ) {
        this.data = new mw.calculators.objectClasses.CalculationData( this.getCalculationData() );
                                massUnits += '/' + doseUnitsByBase.time;
                            }


                            // For whatever reason math.format will simplify the units, but math.formatUnits will not
        this.type = this.type ? this.type : TYPE_NUMBER;
                            // as a hack, we recreate a new unit value with the correct formatting of the result
                            value.dose[ iDose ].mass[ mathProperty ] = math.unit( math.multiply( doseValue, weightValue ).format() ).to( massUnits );
                        }
                    } else {
                        value.dose[ iDose ].mass[ mathProperty ] = doseValue;
                    }


                    if( data.preparation && value.dose[ iDose ].mass[ mathProperty ] ) {
        this.message = null;
                        // Same hack as above to get units to simplify correctly
        this.value = null;
                        var preparationUnitsByBase = mw.calculators.getUnitsByBase( data.preparation.concentration );
    };


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


                        if( doseUnitsByBase.hasOwnProperty( 'time' ) ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.recalculate = function() {
                            volumeUnits += '/' + doseUnitsByBase.time;
        this.message = '';
                        }
        this.value = null;


                        value.dose[ iDose ].volume[ mathProperty ] = math.unit( math.multiply( value.dose[ iDose ].mass[ mathProperty ], math.divide( 1, data.preparation.concentration ) ).format() ).to( volumeUnits );
        var data = this.getCalculationDataValues();
                    }
                }
            }


            if( value.dose[ iDose ].mass.hasOwnProperty( 'absoluteMax' ) ) {
        if( data === false ) {
                if( value.dose[ iDose ].mass.hasOwnProperty( 'min' ) && math.smaller( value.dose[ iDose ].mass.absoluteMax, value.dose[ iDose ].mass.min ) ) {
            this.valueUpdated();
                    // Both min and max are larger than the absolute max dose, so just convert to single dose.
                    value.dose[ iDose ].mass.dose = value.dose[ iDose ].mass.absoluteMax;


                    delete value.dose[ iDose ].mass.min;
            return false;
                    delete value.dose[ iDose ].mass.max;
        }


                    if( value.dose[ iDose ].volume.hasOwnProperty( 'absoluteMax' ) ) {
        try {
                        value.dose[ iDose ].volume.dose = value.dose[ iDose ].volume.absoluteMax;
            var value = this.calculate( data );


                        delete value.dose[ iDose ].volume.min;
            if( this.type === TYPE_NUMBER && !isNaN( value ) ) {
                        delete value.dose[ iDose ].volume.max;
                if( this.units ) {
                    }
                     value = value + ' ' + this.units;
                } else if( value.dose[ iDose ].mass.hasOwnProperty( 'max' ) && math.smaller( value.dose[ iDose ].mass.absoluteMax, value.dose[ iDose ].mass.max ) ) {
                }
                     value.dose[ iDose ].mass.max = value.dose[ iDose ].mass.absoluteMax;


                    if( value.dose[ iDose ].volume.hasOwnProperty( 'absoluteMax' ) ) {
                this.value = math.unit( value );
                        value.dose[ iDose ].volume.max = value.dose[ iDose ].volume.absoluteMax;
            } else {
                    }
                this.value = value;
                } else if( value.dose[ iDose ].mass.hasOwnProperty( 'dose' ) && math.smaller( value.dose[ iDose ].mass.absoluteMax, value.dose[ iDose ].mass.dose ) ) {
            }
                    value.dose[ iDose ].mass.dose = value.dose[ iDose ].mass.absoluteMax;
        } catch( e ) {
            console.warn( e.message );


                    if( value.dose[ iDose ].volume.hasOwnProperty( 'absoluteMax' ) ) {
            this.message = e.message;
                        value.dose[ iDose ].volume.dose = value.dose[ iDose ].volume.absoluteMax;
            this.value = null;
                    }
        } finally {
                }
             this.valueUpdated();
             }
         }
         }


         return value;
         return true;
     };
     };


    mw.calculators.objectClasses.DrugDosageCalculation.prototype.doRender = function() {
        var $calculationContainer = $( '.' + this.getContainerClass() );
        if( !$calculationContainer.length ) {
            return;
        }


        $calculationContainer.empty();


        // Drug label
    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
        var drugLabelAttributes = {
         this.recalculate();
            class: 'calculator-DrugDosageCalculator-drug-cell'
         };


         var $drugLabel = $( '<div>', drugLabelAttributes );
         if( typeof this.onRender === 'function' ) {
            this.onRender();
        }


         $drugLabel.append( this.getLabelHtml() );
         this.doRender();


        if( typeof this.onRendered === 'function' ) {
            this.onRendered();
        }
    };


        // Dose column
    mw.calculators.objectClasses.AbstractCalculation.prototype.setDependencies = function() {
        var $dose = $( '<div>', {
         this.data = this.getCalculationData();
            class: 'col-8 calculator-DrugDosageCalculator-dose-cell'
         );


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


         // The options column should only show the preparation if there is a calculated volume
         for( var iCalculationId in calculationIds ) {
        var hasVolume;
            var calculationId = calculationIds[ iCalculationId ];


        if( !this.value || this.value.dosageId === null ) {
            if( !mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
            if( this.value && this.value.hasOwnProperty( 'message' ) ) {
                 throw new Error('Calculation "' + calculationId + '" does not exist for calculation "' + this.id + '"');
                 $dose.append( $( '<i>' ).append( this.value.message ) );
             }
             }
        } else {
            var dosage = this.drug.dosages[ this.value.dosageId ];


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


            var $doseInfo = $( '<div>', {
        var variableIds = this.data.variables.required.concat( this.data.variables.optional );
                class: 'calculator-DrugDosageCalculator-dose-info'
            } );


            if( dosage.population && dosage.population.id !== DEFAULT_DRUG_POPULATION ) {
        for( var iVariableId in variableIds ) {
                $doseInfo
            var variableId = variableIds[ iVariableId ];
                    .append( $( '<div>', {
                        class: 'calculator-DrugDosageCalculator-dose-info-population'
                    } ).append( String( dosage.population ) + ' dosing' ) );


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


             if( dosage.hasInfo() ) {
             mw.calculators.variables[ variableId ].addCalculation( this.id );
                var doseInfoText = mw.calculators.isMobile() ? 'Dosage info' : 'Dosage information';
        }


                var $doseInfoLink = $( '<a>', {
        this.recalculate();
                    'data-toggle': 'collapse',
    };
                    href: '#' + this.getContainerClass() + '-dose-info-row',
                    role: 'button',
                    'aria-expanded': 'false',
                    'aria-controls': this.getContainerClass() + '-dose-info-row'
                } )
                    .append( doseInfoText + '&nbsp;' )
                    .append( $( '<i>', {
                        class: 'far fa-question-circle'
                    } ) );


                $doseInfo
    mw.calculators.objectClasses.AbstractCalculation.prototype.valueUpdated = function() {
                    .append( $( '<div>', {
        for( var iCalculation in this.calculations ) {
                        class: 'calculator-DrugDosageCalculator-dose-info-button'
            calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );
                    } ).append( $doseInfoLink ) );


                 showInfo = true;
            if( calculation ) {
                 calculation.render();
             }
             }
        }
    };


            if( showInfo ) {
                $dose.append( $doseInfo );
            }


            var $doseData = $( '<div>', {
                class: 'calculator-DrugDosageCalculator-dose-data'
            } );


            // This will iterate through the calculated doses. iDose should exactly correspond to doses within dosage
    /**
            // to allow referencing other properties of the dose.
    * Class CalculationData
            for( var iDose in this.value.dose ) {
    * @param {Object} propertyValues
                var dose = dosage.dose[ iDose ];
    * @returns {mw.calculators.objectClasses.CalculationData}
                var doseValue = this.value.dose[ iDose ];
    * @constructor
    */
    mw.calculators.objectClasses.CalculationData = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


                if( dose.name ) {
        var dataTypes = this.getDataTypes();
                    $doseData.append( dose.name + '<br />' );
        var dataRequirements = this.getDataRequirements();
                }


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


                 var administration = dose.getAdministration();
            if( !this[ dataType ] ) {
                var administrationDisplayed = false;
                 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 ];


                var massPerWeightHtml = '';
                    if( this[ dataType ].hasOwnProperty( dataRequirement ) ) {
 
                        for( var iDataId in this[ dataType ][ dataRequirement ] ) {
                if( doseValue.massPerWeight.hasOwnProperty( 'dose' ) ) {
                            var dataId = this[ dataType ][ dataRequirement ][ iDataId ];
                    massPerWeightHtml += mw.calculators.getValueString( doseValue.massPerWeight.dose );
                         }
                } else if( doseValue.massPerWeight.hasOwnProperty( 'min' ) &&
                    doseValue.massPerWeight.hasOwnProperty( 'max' ) ) {
 
                    // getValueString will simplify the value and may adjust the units
                    var massPerWeightMinValue = math.unit( mw.calculators.getValueString( doseValue.massPerWeight.min ) );
                    var massPerWeightMaxValue = math.unit( mw.calculators.getValueString( doseValue.massPerWeight.max ) );
 
                    if( massPerWeightMinValue.formatUnits() !== massPerWeightMaxValue.formatUnits() ) {
                         // If the units between min and max don't match, show both
                        massPerWeightHtml += mw.calculators.getValueString( massPerWeightMinValue );
                     } else {
                     } else {
                         massPerWeightHtml += mw.calculators.getValueNumber( massPerWeightMinValue );
                         this[ dataType ][ dataRequirement ] = [];
                     }
                     }
                    massPerWeightHtml += dash;
                    massPerWeightHtml += mw.calculators.getValueString( massPerWeightMaxValue );
                 }
                 }
            }
        }
    };


                if( massPerWeightHtml ) {
    mw.calculators.objectClasses.CalculationData.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                    if( administration && ! administrationDisplayed ) {
                        massPerWeightHtml += ' ' + administration;
                        administrationDisplayed = true;
                    }


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


                    if( doseValue.mass.hasOwnProperty( 'absoluteMax' ) ) {
    mw.calculators.objectClasses.CalculationData.prototype.getDataTypes = function() {
                        massPerWeightNotesHtml += 'Max: ' + mw.calculators.getValueString( doseValue.mass.absoluteMax );
        return [
                    }
            'calculations',
            'variables'
        ];
    };


                    if( dose.weightCalculation && dose.weightCalculation[ 0 ].id !== 'tbw' ) {
    mw.calculators.objectClasses.CalculationData.prototype.getProperties = function() {
                        if( massPerWeightNotesHtml ) {
        return {
                            massPerWeightNotesHtml += ', ';
            required: [],
                        }
            optional: [
                'calculations',
                'variables'
            ]
        };
    };


                        massPerWeightNotesHtml += dose.weightCalculation[ 0 ].getLabelString();
                    }


                    if( massPerWeightNotesHtml ) {
                        massPerWeightHtml += ' (' + massPerWeightNotesHtml + ')';
                    }


                    massPerWeightHtml = $( '<li>' ).append( massPerWeightHtml );
    mw.calculators.objectClasses.CalculationData.prototype.merge = function() {
        var mergedData = new mw.calculators.objectClasses.CalculationData();


                    $doseList.append( massPerWeightHtml );
        var data = [ this ].concat( Array.prototype.slice.call( arguments ) );
                }


                var massHtml = '';
        var dataTypes = this.getDataTypes();


                if( doseValue.mass.hasOwnProperty( 'dose' ) ) {
        for( var iData in data ) {
                    massHtml += mw.calculators.getValueString( doseValue.mass.dose );
            for( var iDataType in dataTypes ) {
                 } else if( doseValue.mass.hasOwnProperty( 'min' ) &&
                 var dataType = dataTypes[ iDataType ];
                    doseValue.mass.hasOwnProperty( 'max' ) ) {


                    // getValueString will simplify the value and may adjust the units
                mergedData[ dataType ].required = mergedData[ dataType ].required
                     var massMinValue = math.unit( mw.calculators.getValueString( doseValue.mass.min ) );
                     .concat( data[ iData ][ dataType ].required )
                     var massMaxValue = math.unit( mw.calculators.getValueString( doseValue.mass.max ) );
                     .filter( mw.calculators.uniqueValues );


                    if( massMinValue.formatUnits() !== massMaxValue.formatUnits() ) {
                mergedData[ dataType ].optional = mergedData[ dataType ].optional
                        // If the units between min and max don't match, show both
                    .concat( data[ iData ][ dataType ].optional )
                        massHtml += mw.calculators.getValueString( massMinValue );
                     .filter( mw.calculators.uniqueValues );
                     } else {
            }
                        massHtml += mw.calculators.getValueNumber( massMinValue );
        }
                    }


                    massHtml += dash;
        return mergedData;
                    massHtml += mw.calculators.getValueString( massMaxValue );
    };
                }


                if( massHtml ) {
                    if( administration && ! administrationDisplayed ) {
                        massHtml += ' ' + administration;
                        administrationDisplayed = true;
                    }


                    if( dose.weightCalculation.length && doseValue.weightCalculation.id !== dose.weightCalculation[ 0 ].id ) {
                        var weightCalculationLabel = doseValue.weightCalculation.getLabelString();


                        massHtml += '&nbsp; (' + weightCalculationLabel + '&nbsp;' + $( '<i>', {
                            class: 'far fa-question-circle'
                        } )[ 0 ].outerHTML + ')';
                    }


                    massHtml = $( '<li>' ).append( massHtml );


                    $doseList.append( massHtml );
    /**
                }
    * 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 );


                var volumeHtml = '';
        this.initialize();
    };


                if( doseValue.volume.hasOwnProperty( 'dose' ) ) {
    mw.calculators.objectClasses.SimpleCalculation.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculation.prototype );
                    volumeHtml += mw.calculators.getValueString( doseValue.volume.dose );
                } else if( doseValue.volume.hasOwnProperty( 'min' ) &&
                    doseValue.volume.hasOwnProperty( 'max' ) ) {


                    // getValueString will simplify the value and may adjust the units
                    var volumeMinValue = math.unit( mw.calculators.getValueString( doseValue.volume.min ) );
                    var volumeMaxValue = math.unit( mw.calculators.getValueString( doseValue.volume.max ) );


                    if( volumeMinValue.formatUnits() !== volumeMaxValue.formatUnits() ) {
    mw.calculators.objectClasses.SimpleCalculation.prototype.hasInfo = function() {
                        // If the units between min and max don't match, show both
        return this.description || this.formula || this.references.length;
                        volumeHtml += mw.calculators.getValueString( volumeMinValue );
    };
                    } else {
                        volumeHtml += mw.calculators.getValueNumber( volumeMinValue );
                    }
 
                    volumeHtml += dash;
                    volumeHtml += mw.calculators.getValueString( doseValue.volume.max );
                }
 
                if( volumeHtml ) {
                    if( administration && ! administrationDisplayed ) {
                        volumeHtml += ' ' + administration;
                        administrationDisplayed = true;
                    }


                    volumeHtml = $( '<li>' ).append( volumeHtml );
    mw.calculators.objectClasses.SimpleCalculation.prototype.getLabelHtml = function() {
        var labelHtml = this.getLabelString();


                    $doseList.append( volumeHtml );
        if( this.link ) {
            var href = this.link;


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


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


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


        return labelHtml;
    };


        // Options column
    mw.calculators.objectClasses.SimpleCalculation.prototype.getLabelString = function() {
        var $options = $( '<div>', {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
            class: 'col-4 calculator-DrugDosageCalculator-options-cell'
    };
        } );


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


         if( indications.length ) {
         return this.mergeProperties( inheritedProperties, {
             $options.append( mw.calculators.getVariable( this.getVariableIds().indication ).createInput({
             required: [
                 class: 'calculator-container-input-DrugDosageCalculator-options',
                 'name'
                 hideLabelMobile: true,
            ],
                 inline: true
            optional: [
             } ) );
                'abbreviation',
        }
                 'digits',
                'formula',
                'link',
                 'units'
             ]
        } );
    };


        var routes = this.drug.getRoutes();
    mw.calculators.objectClasses.SimpleCalculation.prototype.getValueString = function() {
 
         if( this.message ) {
         if( routes.length ) {
             return this.message;
             $options.append( mw.calculators.getVariable( this.getVariableIds().route  ).createInput({
        } else if( typeof this.value === 'object' && this.value.hasOwnProperty( 'value' ) ) {
                class: 'calculator-container-input-DrugDosageCalculator-options',
            return mw.calculators.getValueString( this.value );
                hideLabelMobile: true,
        } else {
                inline: true
             return String( this.value );
             } ) );
         }
         }
    };


        // Don't show preparations if there isn't a dose with volume
    mw.calculators.objectClasses.SimpleCalculation.prototype.doRender = function() {
        if( hasVolume ) {
        var $calculationContainer = $( '.' + this.getContainerClass() );
            var preparations = this.drug.getPreparations();


            if( preparations.length ) {
        if( !$calculationContainer.length ) {
                $options.append( mw.calculators.getVariable( this.getVariableIds().preparation  ).createInput({
            return;
                    class: 'calculator-container-input-DrugDosageCalculator-options',
                    hideLabelMobile: true,
                    inline: true
                } ) );
            }
         }
         }


         $calculationContainer
         var valueString = this.getValueString();
            .append( $( '<div>', {
                    class: 'col-12 border'
                } ).append(
                    $drugLabel,
                    $( '<div>', {
                        class: 'row calculator-DrugDosageCalculator-dosage-row'
                    } )
                        .append(
                            $dose,
                            $options
                        )
                )
            );


        var inputVariableIds = this.data.variables.required.concat( this.data.variables.optional );
        var missingVariableInputs = [];


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


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


         var calculation = this;
         var calculation = this;
Line 1,279: Line 1,355:
             $( this ).empty();
             $( this ).empty();


 
            var isTable = this.tagName.toLowerCase() === 'tr';
 


             var $infoButton = null;
             var $infoButton = null;


             if( this.hasInfo() ) {
             if( calculation.hasInfo() ) {
                 $infoButton = $( '<a>', {
                 $infoButton = $( '<a>', {
                     'data-toggle': 'collapse',
                     'data-toggle': 'collapse',
                     href: '#' + this.getContainerClass() + '-info',
                     href: '#' + calculation.getContainerClass() + '-info',
                     role: 'button',
                     role: 'button',
                     'aria-expanded': 'false',
                     'aria-expanded': 'false',
                     'aria-controls': this.getContainerClass() + '-info'
                     'aria-controls': calculation.getContainerClass() + '-info'
                 } )
                 } )
                     .append( $( '<i>', {
                     .append( $( '<i>', {
                         class: 'far fa-question-circle'
                         class: 'far fa-question-circle'
                     } ) );
                     } ) );
            }


                 $label
            var labelHtml = calculation.getLabelHtml();
                     .append( $( '<span>', {
 
                            class: 'calculator-calculation-column-label-info'
            if( isTable ) {
                         } )
                if( calculation.hasInfo() ) {
                            .append( $infoButton )
                    labelHtml += $( '<span>', {
                    );
                        class: 'calculator-SimpleCalculator-info'
                    } ).append( $infoButton )[ 0 ].outerHTML;
                }
 
                 $( this )
                     .append( $( '<th>', {
                        class: 'calculator-SimpleCalculator-calculation-cell',
                        html: labelHtml
                    } ) )
                    .append( $( '<td>', {
                        class: 'calculator-SimpleCalculator-value-cell',
                         html: valueString
                    } ) );
            } else {
                $( this )
                    .append( labelHtml + $infoButton[ 0 ].outerHTML + ': ' + valueString );
             }
             }


Line 1,344: Line 1,435:
                 }
                 }


                 $infoContainer = $( '<tr>', {
                 if( isTable ) {
                    id: infoContainerId,
                    $infoContainer = $( '<tr>', {
                    class: 'collapse'
                        id: infoContainerId,
                } )
                        class: 'collapse'
                    .append( $( '<td>', {
                    } )
                        colspan: 2
                        .append( $( '<td>', {
                     } ).append( infoHtml ) );
                            colspan: 2
 
                        } ).append( infoHtml ) );
                } else {
                    $infoContainer = $( '<div>', {
                        id: infoContainerId,
                        class: 'collapse'
                     } ).append( infoHtml );
                }


                 $( this ).after( $infoContainer );
                 $( this ).after( $infoContainer );
             }
             }
        } );
    };
    mw.calculators.objectClasses.DrugDosageCalculation.prototype.getCalculationData = function() {
        var inputData = new mw.calculators.objectClasses.CalculationData();
        // Add variables created by this calculation
        var variableIds = this.getVariableIds();
        for( var variableType in variableIds ) {
            inputData.variables.optional.push( variableIds[ variableType ] );
        }
        var dataTypes = inputData.getDataTypes();
        // Data is only actually required if it is required by every dosage for the drug.
        // Data marked as required by an individual dosage that does not appear in every
        // dosage will be converted to optional.
        var requiredInputData = new mw.calculators.objectClasses.CalculationData();
        // Need a way to tell the first iteration of the loop to initialize the required variables to a value that
        // is distinct from the empty array (populated across loop using array intersect, so could become [] and shouldn't
        // reinitialize).
        var initializeRequiredData = true;
        // Iterate through each dosage to determine variable dependency
        for( var iDosage in this.drug.dosages ) {
            var dosageInputData = this.drug.dosages[ iDosage ].getCalculationData();


             inputData = inputData.merge( dosageInputData );
             if( missingVariableInputs.length ) {
 
                var variablesContainerClass = 'calculator-SimpleCalculator-variables ' + calculation.getContainerClass() + '-variables';
            for( var iDataType in dataTypes ) {
                 var inputGroup = mw.calculators.createInputGroup( missingVariableInputs );
                 var dataType = dataTypes[ iDataType ];


                 if( initializeRequiredData ) {
                 if( isTable ) {
                     requiredInputData[ dataType ].required = inputData[ dataType ].required;
                     $variablesContainer =  $( '<tr>' )
                        .append( $( '<td>', {
                            class: variablesContainerClass,
                            colspan: 2
                        } ).append( inputGroup ) );
                 } else {
                 } else {
                     // Data is only truly required if it is required by all dosage calculations, so use array intersection
                     $variablesContainer = $( '<div>', {
                    requiredInputData[ dataType ].required = requiredInputData[ dataType ].required.filter( function( index ) {
                         class: variablesContainerClass
                         return dosageInputData[ dataType ].required.indexOf( index ) !== -1;
                     } ).append( inputGroup );
                     } );
                 }
                 }
            }


            initializeRequiredData = false;
                $( this ).after( $variablesContainer );
        }


        for( var iDataType in dataTypes ) {
                missingVariableInputs = [];
            var dataType = dataTypes[ iDataType ];
             }
 
         } );
            // Move any data marked required in inputData to optional if it not actually required (i.e. doesn't appear
            // in requiredInputData).
            inputData[ dataType ].optional = inputData[ dataType ].optional.concat( inputData[ dataType ].required.filter( function( index ) {
                return requiredInputData[ dataType ].required.indexOf( index ) === -1;
             } ) ).filter( mw.calculators.uniqueValues );
 
            inputData[ dataType ].required = requiredInputData[ dataType ].required;
         }
 
        return inputData;
     };
     };


    mw.calculators.objectClasses.DrugDosageCalculation.prototype.getCalculationDataValues = function() {
        var data = mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationDataValues.call( this );


        data.drug = this.drug;


        data.indication = data[ this.getVariablePrefix() + 'indication' ] !== null ?
            mw.calculators.getDrugIndication( mw.calculators.getVariable( this.getVariableIds().indication ).getValue() ) :
            null;


        delete data[ this.getVariablePrefix() + 'indication' ];


        data.preparation = data[ this.getVariablePrefix() + 'preparation' ] !== null ?
    /**
            this.drug.preparations[ mw.calculators.getVariable( this.getVariableIds().preparation ).getValue() ] :
    * Class AbstractCalculator
            null;
    * @param {Object} propertyValues
 
    * @returns {mw.calculators.objectClasses.AbstractCalculator}
        delete data[ this.getVariablePrefix() + 'preparation' ];
    * @constructor
    */
    mw.calculators.objectClasses.AbstractCalculator = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
    };


        data.route = data[ this.getVariablePrefix() + 'route' ] !== null ?
    mw.calculators.objectClasses.AbstractCalculator.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
            mw.calculators.getDrugRoute( mw.calculators.getVariable( this.getVariableIds().route ).getValue() ) :
            null;


        delete data[ this.getVariablePrefix() + 'route' ];
    mw.calculators.objectClasses.AbstractCalculator.prototype.getCalculatorClass = function() {
 
         return '';
         return data;
     };
     };


 
     mw.calculators.objectClasses.AbstractCalculator.prototype.getContainerClass = function() {
     mw.calculators.objectClasses.DrugDosageCalculation.prototype.getLabelHtml = function() {
         return 'calculator-' + this.module + '-' + this.id;
         var $label = $( '<a>', {
            class: 'calculator-DrugDosageCalculator-drug-name',
            href: mw.util.getUrl( this.drug.name ),
            text: this.drug.name
        } ).css( 'background-color', '#fff' );
 
        var highlightColor = this.drug.color.getHighlightColor();
 
        if( highlightColor ) {
            var highlightContainerAttributes = {
                class: 'calculator-DrugDosageCalculator-drug-highlight'
            };
 
            var highlightContainerCss = {};
 
            highlightContainerCss[ 'background' ] = highlightColor;
 
            $label = $( '<span>', highlightContainerAttributes ).append( $label ).css( highlightContainerCss );
        }
 
        var primaryColor = this.drug.color.getPrimaryColor();
 
        if( primaryColor ) {
            var backgroundContainerAttributes = {
                class: 'calculator-DrugDosageCalculator-drug-background'
            };
 
            var backgroundContainerCss = {};
 
            if( this.drug.color.isStriped() ) {
                backgroundContainerCss[ 'background' ] = 'repeating-linear-gradient(135deg,rgba(0,0,0,0),rgba(0,0,0,0)10px,rgba(255,255,255,1)10px,rgba(255,255,255,1)20px),' + primaryColor;
            } else {
                backgroundContainerCss[ 'background'] = primaryColor;
            }
 
            $label = $( '<span>', backgroundContainerAttributes ).append( $label ).css( backgroundContainerCss );
        }
 
        return $label;
     };
     };


     mw.calculators.objectClasses.DrugDosageCalculation.prototype.getProperties = function() {
     mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties = function() {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();
         return {
 
         return this.mergeProperties( inheritedProperties, {
             required: [
             required: [
                 'drug'
                 'id',
                'module',
                'name',
                'calculations'
             ],
             ],
             optional: []
             optional: [
        } );
                'onRender',
    };
                'onRendered'
 
             ]
    mw.calculators.objectClasses.DrugDosageCalculation.prototype.getVariableIds = function() {
        return {
            indication: this.getVariablePrefix() + 'indication',
            preparation: this.getVariablePrefix() + 'preparation',
             route: this.getVariablePrefix() + 'route'
         };
         };
     };
     };


     mw.calculators.objectClasses.DrugDosageCalculation.prototype.getVariableOptions = function( variableId ) {
     mw.calculators.objectClasses.AbstractCalculator.prototype.render = function() {
         if( variableId === this.getVariablePrefix() + 'indication' ) {
         if( typeof this.onRender === 'function' ) {
            return this.drug.getIndications();
             this.onRender();
        } else if( variableId === this.getVariablePrefix() + 'preparation' ) {
             // Exclude preparations which require dilution
            return this.drug.getPreparations( true );
        } else if( variableId === this.getVariablePrefix() + 'route' ) {
            return this.drug.getRoutes();
         }
         }
    };
    mw.calculators.objectClasses.DrugDosageCalculation.prototype.getVariablePrefix = function() {
        return this.drug.id + '-';
    };
    mw.calculators.objectClasses.DrugDosageCalculation.prototype.initialize = function() {
        if( typeof this.drug === 'string' ) {
            var drug = mw.calculators.getDrug( this.drug );


            if( !drug ) {
        this.doRender();
                throw new Error( 'DrugDosage references drug "' + this.drug + '" which is not defined' );
            }


             this.drug = drug;
        if( typeof this.onRendered === 'function' ) {
             this.onRendered();
         }
         }
        this.updateVariables();
        mw.calculators.objectClasses.AbstractCalculation.prototype.initialize.call( this );
     };
     };


    mw.calculators.objectClasses.DrugDosageCalculation.prototype.updateVariables = function() {
        var variableIds = this.getVariableIds();


        for( var variableType in variableIds ) {
    mw.calculators.objectClasses.AbstractCalculator.prototype.doRender = function() {};
            var variableId = variableIds[ variableType ];
            var variableOptions = this.getVariableOptions( variableId );
            var variableOptionValues = {};
            var defaultOption = 0;


            for( var iVariableOption in variableOptions ) {
                var variableOption = variableOptions[ iVariableOption ];


                defaultOption = variableOption.default ? iVariableOption : defaultOption;
                variableOptionValues[ variableOption.id ] = String( variableOption );
            }
            var defaultValue = variableOptions.length ? variableOptions[ defaultOption ].id : null;
            var variable = mw.calculators.getVariable( variableId );
            if( !variable ) {
                var newVariable = {};
                newVariable[ variableId ] = {
                    name: variableType.charAt(0).toUpperCase() + variableType.slice(1),
                    type: 'string',
                    defaultValue: defaultValue,
                    options: variableOptionValues
                };
                mw.calculators.addVariables( newVariable );
            } else {
                // Probably not ideal to reach into the variable to change these things directly
                // Perhaps add helper functions to variable class
                mw.calculators.variables[ variableId ].defaultValue = defaultValue;
                mw.calculators.variables[ variableId ].options = variableOptionValues;
            }
        }
    };
    mw.calculators.addDrugCalculators = function( moduleId, drugCalculatorData, className ) {
        className = className ? className : 'DrugDosageCalculator';
        for( var drugCalculatorId in drugCalculatorData ) {
            drugCalculatorData[ drugCalculatorId ].module = moduleId;
            for( var iCalculation in drugCalculatorData[ drugCalculatorId].calculations ) {
                drugCalculatorData[ drugCalculatorId].calculations[ iCalculation ] = moduleId + '-' +
                    drugCalculatorData[ drugCalculatorId].calculations[ iCalculation ];
            }
        }
        mw.calculators.addCalculators( moduleId, drugCalculatorData, className );
    };






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


     mw.calculators.objectClasses.DrugDosageCalculator.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculator.prototype );
     mw.calculators.objectClasses.SimpleCalculator.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculator.prototype );


     mw.calculators.objectClasses.DrugDosageCalculator.prototype.doRender = function() {
     mw.calculators.objectClasses.SimpleCalculator.prototype.doRender = function() {
         var $calculatorContainer = $( '.' + this.getContainerClass() );
         var $calculatorContainer = $( '.' + this.getContainerClass() );


Line 1,619: Line 1,554:


         $calculatorContainer.addClass( this.getCalculatorClass() );
         $calculatorContainer.addClass( this.getCalculatorClass() );
        if( this.css ) {
            $calculatorContainer.css( this.css );
        }


         $calculatorContainer.empty();
         $calculatorContainer.empty();
Line 1,626: Line 1,565:
         } ) );
         } ) );


         var $calculationsContainer = $( '<div>', {
         var $calculationsContainer;
             class: 'container-fluid'
 
         } );
        if( this.table ) {
            $calculationsContainer = $( '<table>', {
                class: 'wikitable'
             } ).append( '<tbody>' );
 
            $calculationsContainer
                .append( $( '<tr>' )
                    .append(
                        $( '<th>', {
                            class: this.getCalculatorClass() + '-calculation-header'
                        } ).text( 'Calculation' ),
                        $( '<th>', {
                            class: this.getCalculatorClass() + '-value-header'
                        }  ).text( 'Value' )
                    )
                );
         } else {
            $calculationsContainer = $( '<div>' );
        }


         $calculatorContainer.append( $calculationsContainer );
         $calculatorContainer.append( $calculationsContainer );
Line 1,634: Line 1,591:
         for( var iCalculationId in this.calculations ) {
         for( var iCalculationId in this.calculations ) {
             var calculation = mw.calculators.getCalculation( this.calculations[ iCalculationId ] );
             var calculation = mw.calculators.getCalculation( this.calculations[ iCalculationId ] );
             var calculationContainerClass = 'row no-gutters ' + calculation.getContainerClass();
             var calculationContainerClass = calculation.getContainerClass();


             var $calculationContainer = $( '<div>', {
             var $calculationContainer = $( '.' + calculationContainerClass );
                class: calculationContainerClass
 
            } );
            // If a container doesn't exist yet, add it
            if( !$calculationContainer.length ) {
                if( this.table ) {
                    $calculationContainer = $( '<tr>', {
                        class: calculationContainerClass
                    } );
                } else {
                    $calculationContainer = $( '<div>', {
                        class: calculationContainerClass
                    } );
                }


            $calculationsContainer.append( $calculationContainer );
                $calculationsContainer.append( $calculationContainer );
            }


             calculation.render();
             calculation.render();
Line 1,646: Line 1,614:
     };
     };


     mw.calculators.objectClasses.DrugDosageCalculator.prototype.getCalculatorClass = function() {
     mw.calculators.objectClasses.SimpleCalculator.prototype.getCalculatorClass = function() {
         return 'calculator-DrugDosageCalculator';
         return 'calculator-SimpleCalculator';
     };
     };


     mw.calculators.objectClasses.DrugDosageCalculator.prototype.getProperties = function() {
 
     mw.calculators.objectClasses.SimpleCalculator.prototype.getProperties = function() {
         var inheritedProperties = mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties();
         var inheritedProperties = mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties();


         return this.mergeProperties( inheritedProperties, {
         return this.mergeProperties( inheritedProperties, {
             required: [],
             required: [],
             optional: []
             optional: [
                'css',
                'table'
            ]
         } );
         } );
     };
     };
    mw.calculators.initialize();


}() );
}() );

Revision as of 23:12, 21 August 2021

/**
 * @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';
    var DEFAULT_CALCULATOR_CLASS = 'SimpleCalculator';

    // 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 = {
        calculators: {},
        calculations: {},
        objectClasses: {},
        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();
            }
        },
        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
            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();
            }
        },
        addUnitsBases: function( unitsBaseData ) {
            var unitsBases = mw.calculators.createCalculatorObjects( 'UnitsBase', unitsBaseData );

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

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

                try {
                    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,
                    };

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

                mw.calculators.units[ units ] = 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 {
                        // isValueValid will throw an error if invalid, so the catch clause is our else condition
                        if( mw.calculators.variables[ variableId ].isValueValid( cookieValue ) ) {
                            mw.calculators.variables[ variableId ].setValue( cookieValue );
                        }
                    } catch( e ) {
                        // 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 ) {
            var $form = $( '<form>', {

            } );

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

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

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

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

            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;
            }
        },
        getCalculator: function( moduleId, calculatorId ) {
            if( mw.calculators.calculators.hasOwnProperty( moduleId ) &&
                mw.calculators.calculators[ moduleId ].hasOwnProperty( calculatorId ) ) {
                return mw.calculators.calculators[ moduleId ][ calculatorId ];
            } else {
                return null;
            }
        },
        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 ];

                unitsByBase[ units.unit.base.key.toLowerCase() ] = 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( typeof value !== 'object' ) {
                return null;
            }

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

            var absNumber = math.abs( number );

            if( absNumber >= 10 ) {
                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 ) {
                        var newValue = math.unit( newSIValue.toNumber() + ' ' + value.formatUnits().replace( oldSIUnit, newSIUnit ) );

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

            var valueString = String( valueNumber );

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

            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() {
            $( '.calculator' ).each( function() {
                var gadgetModule = 'ext.gadget.calculator-' + $( this ).attr( 'data-module' );

                if( gadgetModule && mw.loader.getState( gadgetModule ) === 'registered' ) {
                    mw.loader.load( gadgetModule );
                }
            } );
        },
        isMobile: function() {
            return window.matchMedia( 'only screen and (max-width: 760px)' ).matches;
        },
        isValueMathObject: function( value ) {
            return value && value.hasOwnProperty( 'value' );
        },
        setCookieValue: function( variableId, value ) {
            mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
                expires: COOKIE_EXPIRATION
            } );
        },
        setValue: function( variableId, value ) {
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return false;
            }

            if( mw.calculators.variables[ variableId ].setValue( value ) ) {
                mw.calculators.setCookieValue( variableId, value );

                return true;
            }

            return false;
        },
        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',
                '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 );
        }

        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.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;

        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 );

        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;

                            mw.calculators.setValue( variableId, newValue );
                        } );

                    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();
                    }

                    mw.calculators.setValue( variableId, newValue );
                } );

            // 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() {
                            mw.calculators.setValue( variableId, $( this ).val() );
                        } );

                    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 );
                }
            }
        }

        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.value !== null ) {
            return this.value;
        } else if( 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.isValueValid = function( value ) {
        if( value === null ) {
            return true;
        }

        if( this.type === TYPE_NUMBER ) {
            if( typeof value !== 'object' ) {
                value = math.unit( value );
            }

            if( this.hasUnits() ) {
                var valueUnits = value.formatUnits();

                if( !valueUnits ) {
                    throw new Error( 'Could not set value for "' + this.id + '": Value must define units' );
                } else if( this.units.indexOf( valueUnits ) === -1 ) {
                    throw new Error( 'Could not set value for "' + this.id + '": Units "' + valueUnits + '" are not valid for this variable' );
                }
            }
        } else if( this.hasOptions() ) {
            if( !this.options.hasOwnProperty( value ) ) {
                throw new Error( 'Could not set value "' + value + '" for "' + this.id + '": Value must define be one of: ' + Object.keys( this.options ).join( ', ' ) );
            }
        }

        return true;
    };

    mw.calculators.objectClasses.Variable.prototype.prepareValue = function( value ) {
        if( !this.isValueValid( value ) ) {
            // isValueValid will throw a meaningful error to the console
            return null;
        }

        if( value !== null ) {
            if( this.type === TYPE_NUMBER ) {
                if( typeof value !== 'object' ) {
                    value = math.unit( value );
                }
            }
        }

        return value;
    };

    mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
        this.value = this.prepareValue( value );

        this.valueUpdated();

        return true;
    };

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

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



    /**
     * 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() {};

    mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerClass = function() {
        return 'calculator-calculation-' + this.id;
    };

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

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

    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 false;
    };

    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.getCalculationData = function() {
        return this.data;
    };

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

        var data = {};
        var missingRequiredData = '';
        var calculationId, calculation, variableId, variable;

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

            if( !calculation ) {
                throw new Error( 'Invalid required calculation "' + calculationId + '" for calculation "' + this.id + '"' );
            } else if( !calculation.hasValue() ) {
                if( missingRequiredData ) {
                    missingRequiredData = missingRequiredData + ', ';
                }

                missingRequiredData = missingRequiredData + calculation.getLabelString();
            } else {
                data[ calculationId ] = calculation.value;
            }
        }

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

            if( !variable ) {
                throw new Error( 'Invalid required variable "' + variableId + '" for calculation "' + this.id + '"' );
            } else if( !variable.hasValue() ) {
                if( missingRequiredData ) {
                    missingRequiredData = missingRequiredData + ', ';
                }

                missingRequiredData = missingRequiredData + variable.getLabelString();
            } else {
                data[ variableId ] = variable.getValue();
            }
        }

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

            return false;
        }

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

            if( !calculation ) {
                throw new Error( 'Invalid optional calculation "' + calculationId + '" for calculation "' + this.id + '"' );
            }

            data[ calculationId ] = calculation.hasValue() ? calculation.value : null;
        }

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

            if( !variable ) {
                throw new Error( 'Invalid optional variable "' + variableId + '" for calculation "' + this.id + '"' );
            }

            data[ variableId ] = variable.hasValue() ? variable.getValue() : null;
        }

        return data;
    };

    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.type = this.type ? this.type : TYPE_NUMBER;

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

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

    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() {
        this.recalculate();

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

        this.doRender();

        if( typeof this.onRendered === 'function' ) {
            this.onRendered();
        }
    };

    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.valueUpdated = function() {
        for( var iCalculation in this.calculations ) {
            calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );

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



    /**
     * 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 ];

                    if( this[ dataType ].hasOwnProperty( dataRequirement ) ) {
                        for( var iDataId in this[ dataType ][ dataRequirement ] ) {
                            var dataId = this[ dataType ][ dataRequirement ][ iDataId ];
                        }
                    } else {
                        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.hasInfo = function() {
        return this.description || this.formula || this.references.length;
    };

    mw.calculators.objectClasses.SimpleCalculation.prototype.getLabelHtml = function() {
        var labelHtml = this.getLabelString();

        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 ] );
            }

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

        return labelHtml;
    };

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

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

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

    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.objectClasses.SimpleCalculation.prototype.doRender = function() {
        var $calculationContainer = $( '.' + this.getContainerClass() );

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

        var valueString = this.getValueString();

        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 );
            }
        }

        var calculation = this;

        $calculationContainer.each( function() {
            $( this ).empty();

            var isTable = this.tagName.toLowerCase() === 'tr';

            var $infoButton = null;

            if( calculation.hasInfo() ) {
                $infoButton = $( '<a>', {
                    'data-toggle': 'collapse',
                    href: '#' + calculation.getContainerClass() + '-info',
                    role: 'button',
                    'aria-expanded': 'false',
                    'aria-controls': calculation.getContainerClass() + '-info'
                } )
                    .append( $( '<i>', {
                        class: 'far fa-question-circle'
                    } ) );
            }

            var labelHtml = calculation.getLabelHtml();

            if( isTable ) {
                if( calculation.hasInfo() ) {
                    labelHtml += $( '<span>', {
                        class: 'calculator-SimpleCalculator-info'
                    } ).append( $infoButton )[ 0 ].outerHTML;
                }

                $( this )
                    .append( $( '<th>', {
                        class: 'calculator-SimpleCalculator-calculation-cell',
                        html: labelHtml
                    } ) )
                    .append( $( '<td>', {
                        class: 'calculator-SimpleCalculator-value-cell',
                        html: valueString
                    } ) );
            } else {
                $( this )
                    .append( labelHtml + $infoButton[ 0 ].outerHTML + ': ' + valueString );
            }

            if( calculation.hasInfo() ) {
                var infoHtml = '';

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

                if( calculation.formula ) {
                    infoHtml += $( '<span>', {
                        class: calculation.getContainerClass() + '-formula'
                    } )[ 0 ].outerHTML;

                    var api = new mw.Api();

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

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

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

                    infoHtml += $references[ 0 ].outerHTML;
                }

                var infoContainerId = calculation.getContainerClass() + '-info';
                var $infoContainer = $( '#' + infoContainerId );

                if( $infoContainer.length ) {
                    $infoContainer.empty();
                }

                if( isTable ) {
                    $infoContainer = $( '<tr>', {
                        id: infoContainerId,
                        class: 'collapse'
                    } )
                        .append( $( '<td>', {
                            colspan: 2
                        } ).append( infoHtml ) );
                } else {
                    $infoContainer = $( '<div>', {
                        id: infoContainerId,
                        class: 'collapse'
                    } ).append( infoHtml );
                }

                $( this ).after( $infoContainer );
            }

            if( missingVariableInputs.length ) {
                var variablesContainerClass = 'calculator-SimpleCalculator-variables ' + calculation.getContainerClass() + '-variables';
                var inputGroup = mw.calculators.createInputGroup( missingVariableInputs );

                if( isTable ) {
                    $variablesContainer =  $( '<tr>' )
                        .append( $( '<td>', {
                            class: variablesContainerClass,
                            colspan: 2
                        } ).append( inputGroup ) );
                } else {
                    $variablesContainer = $( '<div>', {
                        class: variablesContainerClass
                    } ).append( inputGroup );
                }

                $( this ).after( $variablesContainer );

                missingVariableInputs = [];
            }
        } );
    };





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

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

    mw.calculators.objectClasses.AbstractCalculator.prototype.getCalculatorClass = function() {
        return '';
    };

    mw.calculators.objectClasses.AbstractCalculator.prototype.getContainerClass = function() {
        return 'calculator-' + this.module + '-' + this.id;
    };

    mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties = function() {
        return {
            required: [
                'id',
                'module',
                'name',
                'calculations'
            ],
            optional: [
                'onRender',
                'onRendered'
            ]
        };
    };

    mw.calculators.objectClasses.AbstractCalculator.prototype.render = function() {
        if( typeof this.onRender === 'function' ) {
            this.onRender();
        }

        this.doRender();

        if( typeof this.onRendered === 'function' ) {
            this.onRendered();
        }
    };


    mw.calculators.objectClasses.AbstractCalculator.prototype.doRender = function() {};





    /**
     * 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.doRender = function() {
        var $calculatorContainer = $( '.' + this.getContainerClass() );

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

        $calculatorContainer.addClass( this.getCalculatorClass() );

        if( this.css ) {
            $calculatorContainer.css( this.css );
        }

        $calculatorContainer.empty();

        $calculatorContainer.append( $( '<h4>', {
            text: this.name
        } ) );

        var $calculationsContainer;

        if( this.table ) {
            $calculationsContainer = $( '<table>', {
                class: 'wikitable'
            } ).append( '<tbody>' );

            $calculationsContainer
                .append( $( '<tr>' )
                    .append(
                        $( '<th>', {
                            class: this.getCalculatorClass() + '-calculation-header'
                        } ).text( 'Calculation' ),
                        $( '<th>', {
                            class: this.getCalculatorClass() + '-value-header'
                        }  ).text( 'Value' )
                    )
                );
        } else {
            $calculationsContainer = $( '<div>' );
        }

        $calculatorContainer.append( $calculationsContainer );

        for( var iCalculationId in this.calculations ) {
            var calculation = mw.calculators.getCalculation( this.calculations[ iCalculationId ] );
            var calculationContainerClass = calculation.getContainerClass();

            var $calculationContainer = $( '.' + calculationContainerClass );

            // If a container doesn't exist yet, add it
            if( !$calculationContainer.length ) {
                if( this.table ) {
                    $calculationContainer = $( '<tr>', {
                        class: calculationContainerClass
                    } );
                } else {
                    $calculationContainer = $( '<div>', {
                        class: calculationContainerClass
                    } );
                }

                $calculationsContainer.append( $calculationContainer );
            }

            calculation.render();
        }
    };

    mw.calculators.objectClasses.SimpleCalculator.prototype.getCalculatorClass = function() {
        return 'calculator-SimpleCalculator';
    };


    mw.calculators.objectClasses.SimpleCalculator.prototype.getProperties = function() {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties();

        return this.mergeProperties( inheritedProperties, {
            required: [],
            optional: [
                'css',
                'table'
            ]
        } );
    };

    mw.calculators.initialize();

}() );