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

From WikiAnesthesia
Tag: Manual revert
 
(126 intermediate revisions by the same user not shown)
Line 3: Line 3:
  */
  */
( function() {
( function() {
     var COOKIE_EXPIRATION = 12 * 60 * 60;
     mw.calculators.setOptionValue( 'defaultDrugColor', 'default' );
    mw.calculators.setOptionValue( 'defaultDrugPopulation', 'general' );
    mw.calculators.setOptionValue( 'defaultDrugRoute', 'iv' );


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


    mw.calculators = {
                return units;
        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 ) {
         mass: {
             className = className ? className : DEFAULT_CALCULATOR_CLASS;
             toString: function( units ) {
 
                 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 ];


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


            var calculators = mw.calculators.createCalculatorObjects( className, calculatorData );
    mw.calculators.addUnits( {
 
         Eq: {
            // Initalize the calculators property for the module
             baseName: 'mass_eq',
            if( !mw.calculators.calculators.hasOwnProperty( moduleId ) ) {
             prefixes: 'short'
                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 ) {
         mcg: {
             var variables = mw.calculators.createCalculatorObjects( 'Variable', variableData );
             baseName: 'mass',
 
             definition: '1 ug'
             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 ) {
         patch: {
             if( !mw.calculators.objectClasses.hasOwnProperty( className ) ) {
             baseName: 'volume_patch'
                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 ) {
         pct: {
             var $form = $( '<form>', {
             baseName: 'concentration',
 
             definition: '10 mg/mL',
             } );
             formatValue: function( value ) {
 
                 var pctMatch = value.match( /([\d.]+)\s*?%/ );
             var $formRow = $( '<div>', {
                 class: 'form-row'
            } ).css( 'flex-wrap', 'nowrap' );


            for( var iVariableId in variableIds ) {
                if( pctMatch ) {
                var variableId = variableIds[ iVariableId ];
                    var pctValue = pctMatch[ 1 ];


                if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                     value = pctValue + '% (' + 10 * pctValue + ' mg/mL)';
                     throw new Error( 'Invalid variable name "' + variableId + '"' );
                 }
                 }


                 $formRow.append( mw.calculators.variables[ variableId ].createInput() );
                 return value;
             }
             }
            return $form.append( $formRow );
         },
         },
         getCookieKey: function( variableId ) {
         pill: {
             return 'calculators-var-' + variableId;
             baseName: 'volume_pill'
         },
         },
         getCookieValue: function( varId ) {
         spray: {
             var cookieValue = mw.cookie.get( mw.calculators.getCookieKey( varId ) );
             baseName: 'volume_spray'
 
            if( !cookieValue ) {
                return null;
            }
 
            return cookieValue;
         },
         },
         getCalculation: function( calculationId ) {
         units: {
             if( mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
             baseName: 'mass_units',
                return mw.calculators.calculations[ calculationId ];
            aliases: [
            } else {
                 'unit'
                 return null;
             ]
             }
         },
         },
         getCalculator: function( moduleId, calculatorId ) {
         vial: {
            if( mw.calculators.calculators.hasOwnProperty( moduleId ) &&
             baseName: 'volume_vial'
                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
     * DrugColor
    *
    * @param {Object} properties
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.CalculatorObject}
    * @constructor
     */
     */
     mw.calculators.objectClasses.CalculatorObject = function( properties, propertyValues ) {
     mw.calculators.drugColors = {};
        propertyValues = propertyValues ? propertyValues : {};


        if( properties ) {
    mw.calculators.addDrugColors = function( drugColorData ) {
            if( properties.hasOwnProperty( 'required' ) ) {
        var drugColors = mw.calculators.createCalculatorObjects( 'DrugColor', drugColorData );
                for( var iRequiredProperty in properties.required ) {
                    var requiredProperty = properties.required[ iRequiredProperty ];


                    if( !propertyValues || !propertyValues.hasOwnProperty( requiredProperty ) ) {
        for( var drugColorId in drugColors ) {
                        console.error( 'Missing required property "' + requiredProperty + '"' );
            mw.calculators.drugColors[ drugColorId ] = drugColors[ drugColorId ];
                        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() {
     mw.calculators.getDrugColor = function( drugColorId ) {
         return {
         if( mw.calculators.drugColors.hasOwnProperty( drugColorId ) ) {
            required: [],
             return mw.calculators.drugColors[ drugColorId ];
            optional: []
         } else {
        };
            return null;
    };
         }
 
    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
     * Class DrugColor
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.UnitsBase}
     * @returns {mw.calculators.objectClasses.DrugColor}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.UnitsBase = function( propertyValues ) {
     mw.calculators.objectClasses.DrugColor = function( propertyValues ) {
         var properties = {
         var properties = {
             required: [
             required: [
Line 471: Line 116:
             ],
             ],
             optional: [
             optional: [
                 'toString'
                 'parentColor',
                'primaryColor',
                'highlightColor',
                'striped'
             ]
             ]
         };
         };


         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
         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 );
         this.parentColor = this.parentColor || this.id === mw.calculators.getOptionValue( 'defaultDrugColor' ) ? this.parentColor : mw.calculators.getOptionValue( 'defaultDrugColor' );
     };
     };


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


 
     mw.calculators.objectClasses.DrugColor.prototype.getParentDrugColor = function() {
 
         if( !this.parentColor ) {
 
             return null;
     /**
    * Class Variable
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.Variable}
    * @constructor
    */
    mw.calculators.objectClasses.Variable = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
 
         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
         var parentDrugColor = mw.calculators.getDrugColor( this.parentColor );
        if( Array.isArray( this.options ) ) {
            var options = {};
 
            for( var iOption in this.options ) {
                var option = this.options[ iOption ];
 
                options[ option ] = option;
            }


             this.options = options;
        if( !parentDrugColor ) {
             throw new Error( 'Parent drug color "' + this.parentColor + '" not found for drug color "' + this.id + '"' );
         }
         }


         this.calculations = [];
         return parentDrugColor;
    };


         if( this.defaultValue ) {
    mw.calculators.objectClasses.DrugColor.prototype.getHighlightColor = function() {
             this.defaultValue = this.prepareValue( this.defaultValue );
         if( this.highlightColor ) {
             return this.highlightColor;
        } else if( this.parentColor ) {
            return this.getParentDrugColor().getHighlightColor();
         }
         }
        this.value = null;
     };
     };


     mw.calculators.objectClasses.Variable.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
     mw.calculators.objectClasses.DrugColor.prototype.getPrimaryColor = function() {
 
         if( this.primaryColor ) {
    mw.calculators.objectClasses.Variable.prototype.addCalculation = function( calculationId ) {
            return this.primaryColor;
         if( this.calculations.indexOf( calculationId ) !== -1 ) {
        } else if( this.parentColor ) {
             return;
             return this.getParentDrugColor().getPrimaryColor();
         }
         }
        this.calculations.push( calculationId );
     };
     };


     mw.calculators.objectClasses.Variable.prototype.createInput = function( inputOptions ) {
     mw.calculators.objectClasses.DrugColor.prototype.isStriped = function() {
         if( !inputOptions ) {
         if( this.striped !== null ) {
             inputOptions = {};
             return this.striped;
        } else if( this.parentColor ) {
            return this.getParentDrugColor().isStriped();
         }
         }
    };


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


        var inputContainerCss = {};
    mw.calculators.drugPopulations = {};


        // Initialize label attributes
    mw.calculators.addDrugPopulations = function( drugPopulationData ) {
         var labelAttributes = {
         var drugPopulations = mw.calculators.createCalculatorObjects( 'DrugPopulation', drugPopulationData );
            for: inputId,
            html: this.getLabelString()
        };


         if( inputOptions.hideLabel || ( inputOptions.hideLabelMobile && mw.calculators.isMobile() ) ) {
         for( var drugPopulationId in drugPopulations ) {
             labelAttributes.class = 'sr-only';
             mw.calculators.drugPopulations[ drugPopulationId ] = drugPopulations[ drugPopulationId ];
         }
         }
    };


        var labelCss = {};
    mw.calculators.getDrugPopulation = function( drugPopulationId ) {
 
         if( mw.calculators.drugPopulations.hasOwnProperty( drugPopulationId ) ) {
         if( inputOptions.inline ) {
             return mw.calculators.drugPopulations[ drugPopulationId ];
             inputContainerTag = '<span>';
        } else {
 
             return null;
            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 );
    /**
    * 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'
            ]
        };


         var value = this.getValue();
         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
 
        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 ) {
        if( this.variables ) {
                     inputValue = number;
            for( var variableId in this.variables ) {
                 if( !mw.calculators.getVariable( variableId ) ) {
                     throw new Error( 'DrugPopulation variable "' + variableId + '" not defined' );
                 }
                 }
            } else {
                inputValue = value;
            }


            // Initialize input options
                this.variables[ variableId ].min = this.variables[ variableId ].hasOwnProperty( 'min' ) ?
            var inputAttributes = {
                    math.unit( this.variables[ variableId ].min ) : null;
                id: inputId,
                class: 'form-control form-control-sm calculator-input calculator-input-text',
                type: 'text',
                autocomplete: 'off',
                inputmode: 'decimal',
                value: inputValue
            };


            // Configure additional options
                this.variables[ variableId ].max = this.variables[ variableId ].hasOwnProperty( 'max' ) ?
            if( this.maxLength ) {
                    math.unit( this.variables[ variableId ].max ) : null;
                inputAttributes.maxlength = this.maxLength;
             }
             }
        } else {
            this.variables = {};
        }
    };


            // Add any additional classes to the input
    mw.calculators.objectClasses.DrugPopulation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
            inputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';


            // Add the input id to the list of classes
    mw.calculators.objectClasses.DrugPopulation.prototype.getCalculationData = function() {
            inputAttributes.class += ' ' + inputId;
        var inputData = new mw.calculators.objectClasses.CalculationData();


            // If the variable has units, create the units input
        for( var variableId in this.variables ) {
            if( this.hasUnits() ) {
            inputData.variables.required.push( variableId );
                // Set the units id
        }
                unitsId = inputId + '-units';


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


                var unitsInputAttributes = {
    mw.calculators.objectClasses.DrugPopulation.prototype.getCalculationDataScore = function( dataValues ) {
                    id: unitsId
        // A return value of -1 indicates the data did not match the population definition
                };


                // Create the units container
        for( var variableId in this.variables ) {
                $unitsContainer = $( '<div>', {
            if( !dataValues.hasOwnProperty( variableId ) ) {
                    class: 'input-group-append'
                return -1;
                } ).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 );
            if( this.variables[ variableId ].min &&
                 }
                ( !dataValues[ variableId ] ||
                     !math.largerEq( dataValues[ variableId ], this.variables[ variableId ].min ) ) ) {
                 return -1;
             }
             }


             // Create the input and add handlers
             if( this.variables[ variableId ].max &&
            var $input = $( '<input>', inputAttributes )
                ( !dataValues[ variableId ] ||
                .on( 'input', function() {
                     !math.smallerEq( dataValues[ variableId ], this.variables[ variableId ].max ) ) ) {
                    var numberValue = $( this ).val();
                 return -1;
 
                    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 );
        // If the data matches the population definition, the score corresponds to the number of variables in the
         } else if( this.type === TYPE_STRING ) {
         // population definition. This should roughly correspond to the specificity of the population.
            if( this.hasOptions() ) {
        return Object.keys( this.variables ).length;
                var optionKeys = Object.keys( this.options );
    };


                if( optionKeys.length === 1 ) {
    mw.calculators.objectClasses.DrugPopulation.prototype.toString = function() {
                    $inputContainer.append( this.options[ optionKeys[ 0 ] ] );
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
                } 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 ];
    * DrugRoute
    */
    mw.calculators.drugRoutes = {};


                        var optionAttributes = {
    mw.calculators.addDrugRoutes = function( drugRouteData ) {
                            value: optionId,
        var drugRoutes = mw.calculators.createCalculatorObjects( 'DrugRoute', drugRouteData );
                            text: displayText
                        };


                        if( optionId === value ) {
        for( var drugRouteId in drugRoutes ) {
                            optionAttributes.selected = true;
            mw.calculators.drugRoutes[ drugRouteId ] = drugRoutes[ drugRouteId ];
                        }
        }
    };


                        $select.append( $( '<option>', optionAttributes ) );
    mw.calculators.getDrugRoute = function( drugRouteId ) {
                    }
        if( mw.calculators.drugRoutes.hasOwnProperty( drugRouteId ) ) {
            return mw.calculators.drugRoutes[ drugRouteId ];
        } else {
            return null;
        }
    };


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


         return $inputContainer;
         this.abbreviation = this.abbreviation ? this.abbreviation : this.name;
     };
     };


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


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


     mw.calculators.objectClasses.Variable.prototype.getValue = function() {
     mw.calculators.objectClasses.DrugRoute.prototype.toString = function() {
         if( this.value !== null ) {
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
            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 );
    * DrugIndication
    };
    */
 
     mw.calculators.drugIndications = {};
     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() ) {
    mw.calculators.addDrugIndications = function( drugIndicationData ) {
                var valueUnits = value.formatUnits();
        var drugIndications = mw.calculators.createCalculatorObjects( 'DrugIndication', drugIndicationData );


                if( !valueUnits ) {
        for( var drugIndicationId in drugIndications ) {
                    throw new Error( 'Could not set value for "' + this.id + '": Value must define units' );
             mw.calculators.drugIndications[ drugIndicationId ] = drugIndications[ drugIndicationId ];
                } 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 ) {
     mw.calculators.getDrugIndication = function( drugIndicationId ) {
         if( !this.isValueValid( value ) ) {
         if( mw.calculators.drugIndications.hasOwnProperty( drugIndicationId ) ) {
             // isValueValid will throw a meaningful error to the console
             return mw.calculators.drugIndications[ drugIndicationId ];
        } else {
             return null;
             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
     * Class DrugIndication
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.AbstractCalculation}
     * @returns {mw.calculators.objectClasses.DrugIndication}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.AbstractCalculation = function( propertyValues ) {
     mw.calculators.objectClasses.DrugIndication = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), 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.DrugIndication.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );


     mw.calculators.objectClasses.AbstractCalculation.prototype.addCalculation = function( calculationId ) {
     mw.calculators.objectClasses.DrugIndication.prototype.getProperties = function() {
        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 {
         return {
             required: [
             required: [
                 'id',
                 'id',
                 'calculate'
                 'name'
             ],
             ],
             optional: [
             optional: [
                 'data',
                 'abbreviation',
                 'description',
                 'default',
                 'onRender',
                 'searchData'
                'onRendered',
                'references',
                'type'
             ]
             ]
         };
         };
     };
     };


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


         return this.value;
         return searchString.trim();
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.hasInfo = function() {
     mw.calculators.objectClasses.DrugIndication.prototype.toString = function() {
         return false;
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
     };
     };


    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 ];
    * Drug
            calculation = mw.calculators.getCalculation( calculationId );
    */
    mw.calculators.drugs = {};


            if( !calculation ) {
    mw.calculators.addDrugs = function( drugData ) {
                throw new Error( 'Invalid required calculation "' + calculationId + '" for calculation "' + this.id + '"' );
        var drugs = mw.calculators.createCalculatorObjects( 'Drug', drugData );
            } else if( !calculation.hasValue() ) {
                if( missingRequiredData ) {
                    missingRequiredData = missingRequiredData + ', ';
                }


                missingRequiredData = missingRequiredData + calculation.getLabelString();
        for( var drugId in drugs ) {
             } else {
             mw.calculators.drugs[ drugId ] = drugs[ drugId ];
                data[ calculationId ] = calculation.value;
            }
         }
         }
    };


        for( var iRequiredVariable in calculationData.variables.required ) {
    mw.calculators.addDrugDosages = function( drugId, drugDosageData ) {
            variableId = calculationData.variables.required[ iRequiredVariable ];
        var drug = mw.calculators.getDrug( drugId );
            variable = mw.calculators.getVariable( variableId );


            if( !variable ) {
        if( !drug ) {
                throw new Error( 'Invalid required variable "' + variableId + '" for calculation "' + this.id + '"' );
            throw new Error( 'DrugDosage references drug "' + drugId + '" which is not defined' );
            } else if( !variable.hasValue() ) {
                if( missingRequiredData ) {
                    missingRequiredData = missingRequiredData + ', ';
                }
 
                missingRequiredData = missingRequiredData + variable.getLabelString();
            } else {
                data[ variableId ] = variable.getValue();
            }
         }
         }


         if( missingRequiredData ) {
         drug.addDosages( drugDosageData );
            this.message = missingRequiredData + ' required';
    };


             return false;
    mw.calculators.getDrug = function( drugId ) {
        if( mw.calculators.drugs.hasOwnProperty( drugId ) ) {
             return mw.calculators.drugs[ drugId ];
        } else {
            return null;
         }
         }
    };


        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;
    /**
        }
    * Class Drug
 
    * @param {Object} propertyValues
        for( var iOptionalVariable in calculationData.variables.optional ) {
    * @returns {mw.calculators.objectClasses.Drug}
            variableId = calculationData.variables.optional[ iOptionalVariable ];
    * @constructor
            variable = mw.calculators.getVariable( variableId );
    */
 
    mw.calculators.objectClasses.Drug = function( propertyValues ) {
            if( !variable ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
                throw new Error( 'Invalid optional variable "' + variableId + '" for calculation "' + this.id + '"' );
            }


             data[ variableId ] = variable.hasValue() ? variable.getValue() : null;
        if( !this.color ) {
             this.color = mw.calculators.getOptionValue( 'defaultDrugColor' );
         }
         }


         return data;
         var color = mw.calculators.getDrugColor( this.color );
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.initialize = function() {
         if( !color ) {
         if( typeof this.calculate !== 'function' ) {
             throw new Error( 'Invalid drug color "' + this.color + '" for drug "' + this.id + '"' );
             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.color = color;
         this.calculations = [];


         this.data = new mw.calculators.objectClasses.CalculationData( this.getCalculationData() );
         if( this.preparations ) {
            var preparationData = this.preparations;


        this.type = this.type ? this.type : TYPE_NUMBER;
            this.preparations = [];


        this.message = null;
            this.addPreparations( preparationData );
        this.value = null;
         } else {
    };
            this.preparations = [];
 
    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 {
         if( this.dosages ) {
             var value = this.calculate( data );
             var dosageData = this.dosages;


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


                this.value = math.unit( value );
            this.addDosages( dosageData );
            } else {
        } else {
                this.value = value;
             this.dosages = [];
            }
        } catch( e ) {
            console.warn( e.message );
 
            this.message = e.message;
             this.value = null;
        } finally {
            this.valueUpdated();
         }
         }


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


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


    mw.calculators.objectClasses.Drug.prototype.addDosages = function( dosageData ) {
        var dosages = mw.calculators.createCalculatorObjects( 'DrugDosage', dosageData );


    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
        for( var dosageId in dosages ) {
        this.recalculate();
            dosages[ dosageId ].id = this.dosages.length;


        if( typeof this.onRender === 'function' ) {
            this.dosages.push( dosages[ dosageId ] );
            this.onRender();
         }
         }
    };


         this.doRender();
    mw.calculators.objectClasses.Drug.prototype.addPreparations = function( preparationData ) {
         var preparations = mw.calculators.createCalculatorObjects( 'DrugPreparation', preparationData );


         if( typeof this.onRendered === 'function' ) {
         for( var preparationId in preparations ) {
             this.onRendered();
            preparations[ preparationId ].id = this.preparations.length;
 
             this.preparations.push( preparations[ preparationId ] );
         }
         }
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.setDependencies = function() {
     mw.calculators.objectClasses.Drug.prototype.getIndications = function() {
         this.data = this.getCalculationData();
         var indications = [];


        var calculationIds = this.data.calculations.required.concat( this.data.calculations.optional );
         for( var iDosage in this.dosages ) {
 
             if( this.dosages[ iDosage ].indication ) {
         for( var iCalculationId in calculationIds ) {
                 indications.push( this.dosages[ iDosage ].indication );
            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 );
         return indications.filter( mw.calculators.uniqueValues );
    };


        for( var iVariableId in variableIds ) {
    mw.calculators.objectClasses.Drug.prototype.getPopulations = function( indicationId ) {
            var variableId = variableIds[ iVariableId ];
        var populations = [];


             if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
        for( var iDosage in this.dosages ) {
                 throw new Error('Variable "' + variableId + '" does not exist for calculation "' + this.id + '"');
             if( this.dosages[ iDosage ].population &&
                ( !indicationId || ( this.dosages[ iDosage ].indication && this.dosages[ iDosage ].indication.id === indicationId ) ) ) {
                 populations.push( this.dosages[ iDosage ].population );
             }
             }
            mw.calculators.variables[ variableId ].addCalculation( this.id );
         }
         }


         this.recalculate();
         return populations.filter( mw.calculators.uniqueValues );
     };
     };


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


             if( calculation ) {
        for( var iDosage in this.dosages ) {
                 calculation.render();
             if( this.dosages[ iDosage ].routes.length &&
                ( !indicationId || ( this.dosages[ iDosage ].indication && this.dosages[ iDosage ].indication.id === indicationId ) ) ) {
                 for( var iRoute in this.dosages[ iDosage ].routes ) {
                    routes.push( this.dosages[ iDosage ].routes[ iRoute ] );
                }
             }
             }
         }
         }
        return routes.filter( mw.calculators.uniqueValues );
     };
     };


    mw.calculators.objectClasses.Drug.prototype.getPreparations = function( excludeDilutionRequired ) {
        var preparations = this.preparations.filter( mw.calculators.uniqueValues );


 
         if( excludeDilutionRequired ) {
    /**
             for( var iPreparation in preparations ) {
    * Class CalculationData
                if( preparations[ iPreparation ].dilutionRequired ) {
    * @param {Object} propertyValues
                     delete preparations[ iPreparation ];
    * @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 preparations;
         return [
            'optional',
            'required'
        ];
     };
     };


     mw.calculators.objectClasses.CalculationData.prototype.getDataTypes = function() {
     mw.calculators.objectClasses.Drug.prototype.getProperties = function() {
        return [
            'calculations',
            'variables'
        ];
    };
 
    mw.calculators.objectClasses.CalculationData.prototype.getProperties = function() {
         return {
         return {
             required: [],
             required: [
                'id',
                'name'
            ],
             optional: [
             optional: [
                 'calculations',
                 'color',
                 'variables'
                 'description',
                'dosages',
                'formula',
                'preparations',
                'references',
                'searchData',
                'tradeNames'
             ]
             ]
         };
         };
Line 1,230: Line 574:




    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();
    /**
 
    * DrugPreparation
        for( var iData in data ) {
    */
            for( var iDataType in dataTypes ) {
    mw.calculators.addDrugPreparations = function( drugId, drugPreparationData ) {
                var dataType = dataTypes[ iDataType ];
        var drug = mw.calculators.getDrug( drugId );
 
                mergedData[ dataType ].required = mergedData[ dataType ].required
                    .concat( data[ iData ][ dataType ].required )
                    .filter( mw.calculators.uniqueValues );


                mergedData[ dataType ].optional = mergedData[ dataType ].optional
        if( !drug ) {
                    .concat( data[ iData ][ dataType ].optional )
            throw new Error( 'DrugPreparation references drug "' + drugId + '" which is not defined' );
                    .filter( mw.calculators.uniqueValues );
            }
         }
         }


         return mergedData;
         drug.addPreparations( drugPreparationData );
     };
     };






     /**
     /**
     * Class SimpleCalculation
     * Class DrugPreparation
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.SimpleCalculation}
     * @returns {mw.calculators.objectClasses.DrugPreparation}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.SimpleCalculation = function( propertyValues ) {
     mw.calculators.objectClasses.DrugPreparation = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
         var properties = {
            required: [
                'id',
                'concentration'
            ],
            optional: [
                'default',
                'dilutionRequired',
                'commonDilution'
            ]
        };


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


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


        this.concentration = this.concentration.replace( 'mcg', 'ug' );


    mw.calculators.objectClasses.SimpleCalculation.prototype.hasInfo = function() {
         this.concentration = math.unit( this.concentration );
         return this.description || this.formula || this.references.length;
     };
     };


     mw.calculators.objectClasses.SimpleCalculation.prototype.getLabelHtml = function() {
     mw.calculators.objectClasses.DrugPreparation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        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() {
     mw.calculators.objectClasses.DrugPreparation.prototype.getVolumeUnits = function() {
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
        // 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.SimpleCalculation.prototype.getProperties = function() {
     mw.calculators.objectClasses.DrugPreparation.prototype.toString = function() {
         var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();
         return mw.calculators.getValueString( this.concentration );
 
        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 = [];
    * Class DrugDosage
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.DrugDosage}
    * @constructor
    */
    mw.calculators.objectClasses.DrugDosage = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


         for( var iInputVariableId in inputVariableIds ) {
         var drugIndication = mw.calculators.getDrugIndication( this.indication );
            var variableId = inputVariableIds[ iInputVariableId ];


            if( !$( '#calculator-input-' + variableId ).length ) {
        if( !drugIndication ) {
                missingVariableInputs.push( variableId );
            throw new Error( 'Invalid indication "' + this.indication + '" for drug dosage' );
            }
         }
         }


         var calculation = this;
         this.indication = drugIndication;


         $calculationContainer.each( function() {
         this.population = this.population ? this.population : mw.calculators.getOptionValue( 'defaultDrugPopulation' );
            $( this ).empty();


            var isTable = this.tagName.toLowerCase() === 'tr';
        var drugPopulation = mw.calculators.getDrugPopulation( this.population );


            var $infoButton = null;
        if( !drugPopulation ) {
 
            throw new Error( 'Invalid population "' + this.population + '" for drug dosage' );
            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();
        this.population = drugPopulation;


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


                $( this )
        this.routes = this.routes ? this.routes : [ mw.calculators.getOptionValue( 'defaultDrugRoute' ) ];
                    .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() ) {
        if( !Array.isArray( this.routes ) ) {
                var infoHtml = '';
            this.routes = [ this.routes ];
 
        }
                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();
        drugRoutes = [];


                    api.parse( calculation.formula ).then( function( result ) {
        for( var iRoute in this.routes ) {
                        $( '.' + calculation.getContainerClass() + '-formula' ).html( result );
            var drugRouteId = this.routes[ iRoute ];
                    } );
            var drugRoute = mw.calculators.getDrugRoute( drugRouteId );
                }


                if( calculation.references.length ) {
            if( !drugRoute ) {
                    var $references = $( '<ol>' );
                throw new Error( 'Invalid route "' + drugRouteId + '" for drug dosage' );
 
                    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 ) {
             drugRoutes[ iRoute ] = drugRoute;
                var variablesContainerClass = 'calculator-SimpleCalculator-variables ' + calculation.getContainerClass() + '-variables';
        }
                var inputGroup = mw.calculators.createInputGroup( missingVariableInputs );


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


                $( this ).after( $variablesContainer );
        // Add the dose objects to the drug
        var drugDoseData = this.dose;
        this.dose = [];


                missingVariableInputs = [];
         this.addDoses( drugDoseData );
            }
         } );
     };
     };


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


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


        var doses = mw.calculators.createCalculatorObjects( 'DrugDose', drugDoseData );


        for( var doseId in doses ) {
            doses[ doseId ].id = this.dose.length;


    /**
            this.dose.push( doses[ doseId ] );
    * 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.DrugDosage.prototype.getCalculationData = function() {
        var inputData = new mw.calculators.objectClasses.CalculationData();
 
        inputData = inputData.merge( this.population.getCalculationData() );


    mw.calculators.objectClasses.AbstractCalculator.prototype.getCalculatorClass = function() {
        for( var iDose in this.dose ) {
         return '';
            inputData = inputData.merge( this.dose[ iDose ].getCalculationData() );
    };
         }


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


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


     mw.calculators.objectClasses.AbstractCalculator.prototype.render = function() {
     mw.calculators.objectClasses.DrugDosage.prototype.getRouteString = function() {
         if( typeof this.onRender === 'function' ) {
         var routeString = '';
             this.onRender();
 
        for( var iRoute in this.routes ) {
            routeString += routeString ? '/' : '';
             routeString += this.routes[ iRoute ].abbreviation;
         }
         }


         this.doRender();
         return routeString;
    };


        if( typeof this.onRendered === 'function' ) {
    mw.calculators.objectClasses.DrugDosage.prototype.hasInfo = function() {
            this.onRendered();
        return this.description;
        }
     };
     };
    mw.calculators.objectClasses.AbstractCalculator.prototype.doRender = function() {};




Line 1,535: Line 758:


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


    mw.calculators.objectClasses.SimpleCalculator.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculator.prototype );
        if( this.weightCalculation ) {
            var weightCalculationIds = this.weightCalculation;
 
            // weightCalculation property will contain references to the actual objects, so reinitialize
            this.weightCalculation = [];


    mw.calculators.objectClasses.SimpleCalculator.prototype.doRender = function() {
            if( !Array.isArray( weightCalculationIds ) ) {
        var $calculatorContainer = $( '.' + this.getContainerClass() );
                weightCalculationIds = [ weightCalculationIds ];
            }


        if( !$calculatorContainer.length ) {
            for( var iWeightCalculation in weightCalculationIds ) {
            return;
                var weightCalculationId = weightCalculationIds[ iWeightCalculation ];
        }
                var weightCalculation = mw.calculators.getCalculation( weightCalculationId );


        $calculatorContainer.addClass( this.getCalculatorClass() );
                if( !weightCalculation ) {
                    throw new Error( 'Drug dose references weight calculation "' + weightCalculationId + '" which is not defined' );
                }


        if( this.css ) {
                this.weightCalculation.push( weightCalculation );
             $calculatorContainer.css( this.css );
            }
        } else {
             this.weightCalculation = [];
         }
         }


         $calculatorContainer.empty();
         var mathProperties = this.getMathProperties();
        var isWeightDependent = false;
 
        for( var iMathProperty in mathProperties ) {
            var mathProperty = mathProperties[ iMathProperty ];


        $calculatorContainer.append( $( '<h4>', {
            if( this[ mathProperty ] ) {
            text: this.name
                // TODO consider making a UnitsBase.weight.fromString()
        } ) );
                this[ mathProperty ] = this[ mathProperty ].replace( 'kg', 'kgwt' );
                this[ mathProperty ] = this[ mathProperty ].replace( 'mcg', 'ug' );


        var $calculationsContainer;
                this[ mathProperty ] = math.unit( this[ mathProperty ] );


        if( this.table ) {
                if( mw.calculators.isValueDependent( this[ mathProperty ], 'weight' ) ) {
             $calculationsContainer = $( '<table>', {
                    isWeightDependent = true;
                 class: 'wikitable'
                }
             } ).append( '<tbody>' );
             } else {
                 this[ mathProperty ] = null;
             }
        }


            $calculationsContainer
        if( isWeightDependent ) {
                .append( $( '<tr>' )
            // Default is tbw
                    .append(
            this.weightCalculation.push( mw.calculators.getCalculation( 'tbw' ) );
                        $( '<th>', {
                            class: this.getCalculatorClass() + '-calculation-header'
                        } ).text( 'Calculation' ),
                        $( '<th>', {
                            class: this.getCalculatorClass() + '-value-header'
                        }  ).text( 'Value' )
                    )
                );
        } else {
            $calculationsContainer = $( '<div>' );
         }
         }
    };
    mw.calculators.objectClasses.DrugDose.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );


        $calculatorContainer.append( $calculationsContainer );
    mw.calculators.objectClasses.DrugDose.prototype.getAdministration = function() {
        var administration = '';


         for( var iCalculationId in this.calculations ) {
         if( this.frequency ) {
             var calculation = mw.calculators.getCalculation( this.calculations[ iCalculationId ] );
             administration += administration ? ' ' : '';
             var calculationContainerClass = calculation.getContainerClass();
             administration += this.frequency;
        }


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


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


                $calculationsContainer.append( $calculationContainer );
    mw.calculators.objectClasses.DrugDose.prototype.getCalculationData = function() {
            }
        var calculationData = new mw.calculators.objectClasses.CalculationData();


             calculation.render();
        for( var iWeightCalculation in this.weightCalculation ) {
             calculationData.calculations.optional.push( this.weightCalculation[ iWeightCalculation ].id );
         }
         }
        return calculationData;
     };
     };


     mw.calculators.objectClasses.SimpleCalculator.prototype.getCalculatorClass = function() {
     mw.calculators.objectClasses.DrugDose.prototype.getMathProperties = function() {
         return 'calculator-SimpleCalculator';
         return [
            'dose',
            'min',
            'max',
            'absoluteMin',
            'absoluteMax'
        ];
     };
     };


 
     mw.calculators.objectClasses.DrugDose.prototype.getProperties = function() {
     mw.calculators.objectClasses.SimpleCalculator.prototype.getProperties = function() {
         return {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties();
             required: [
 
                'id'
         return this.mergeProperties( inheritedProperties, {
            ],
             required: [],
             optional: [
             optional: [
                 'css',
                 'absoluteMax',
                 'table'
                 'absoluteMin',
                'dose',
                'duration',
                'frequency',
                'min',
                'max',
                'name',
                'text',
                'weightCalculation'
             ]
             ]
         } );
         };
     };
     };
    mw.calculators.initialize();


}() );
}() );

Latest revision as of 20:55, 29 March 2022

/**
 * @author Chris Rishel
 */
( function() {
    mw.calculators.setOptionValue( 'defaultDrugColor', 'default' );
    mw.calculators.setOptionValue( 'defaultDrugPopulation', 'general' );
    mw.calculators.setOptionValue( 'defaultDrugRoute', 'iv' );

    mw.calculators.isValueDependent = function( value, variableId ) {
        // This may need generalized to support other variables in the future
        if( variableId === 'weight' ) {
            return value && value.formatUnits().match( /\/[\s(]*?kg/ );
        } else {
            throw new Error( 'Dependence "' + variableId + '" not supported by isValueDependent' );
        }
    };

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

                return units;
            }
        },
        mass: {
            toString: function( units ) {
                units = units.replace( 'ug', 'mcg' );

                return units;
            }
        }
    } );

    mw.calculators.addUnits( {
        Eq: {
            baseName: 'mass_eq',
            prefixes: 'short'
        },
        mcg: {
            baseName: 'mass',
            definition: '1 ug'
        },
        patch: {
            baseName: 'volume_patch'
        },
        pct: {
            baseName: 'concentration',
            definition: '10 mg/mL',
            formatValue: function( value ) {
                var pctMatch = value.match( /([\d.]+)\s*?%/ );

                if( pctMatch ) {
                    var pctValue = pctMatch[ 1 ];

                    value = pctValue + '% (' + 10 * pctValue + ' mg/mL)';
                }

                return value;
            }
        },
        pill: {
            baseName: 'volume_pill'
        },
        spray: {
            baseName: 'volume_spray'
        },
        units: {
            baseName: 'mass_units',
            aliases: [
                'unit'
            ]
        },
        vial: {
            baseName: 'volume_vial'
        }
    } );



    /**
     * DrugColor
     */
    mw.calculators.drugColors = {};

    mw.calculators.addDrugColors = function( drugColorData ) {
        var drugColors = mw.calculators.createCalculatorObjects( 'DrugColor', drugColorData );

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

    mw.calculators.getDrugColor = function( drugColorId ) {
        if( mw.calculators.drugColors.hasOwnProperty( drugColorId ) ) {
            return mw.calculators.drugColors[ drugColorId ];
        } else {
            return null;
        }
    };

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

        this.parentColor = this.parentColor || this.id === mw.calculators.getOptionValue( 'defaultDrugColor' ) ? this.parentColor : mw.calculators.getOptionValue( 'defaultDrugColor' );
    };

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

    mw.calculators.objectClasses.DrugColor.prototype.getParentDrugColor = function() {
        if( !this.parentColor ) {
            return null;
        }

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

        if( !parentDrugColor ) {
            throw new Error( 'Parent drug color "' + this.parentColor + '" not found for drug color "' + this.id + '"' );
        }

        return parentDrugColor;
    };

    mw.calculators.objectClasses.DrugColor.prototype.getHighlightColor = function() {
        if( this.highlightColor ) {
            return this.highlightColor;
        } else if( this.parentColor ) {
            return this.getParentDrugColor().getHighlightColor();
        }
    };

    mw.calculators.objectClasses.DrugColor.prototype.getPrimaryColor = function() {
        if( this.primaryColor ) {
            return this.primaryColor;
        } else if( this.parentColor ) {
            return this.getParentDrugColor().getPrimaryColor();
        }
    };

    mw.calculators.objectClasses.DrugColor.prototype.isStriped = function() {
        if( this.striped !== null ) {
            return this.striped;
        } else if( this.parentColor ) {
            return this.getParentDrugColor().isStriped();
        }
    };





    /**
     * DrugPopulation
     */

    mw.calculators.drugPopulations = {};

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

        for( var drugPopulationId in drugPopulations ) {
            mw.calculators.drugPopulations[ drugPopulationId ] = drugPopulations[ drugPopulationId ];
        }
    };

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



    /**
     * 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( this.variables ) {
            for( var variableId in this.variables ) {
                if( !mw.calculators.getVariable( variableId ) ) {
                    throw new Error( 'DrugPopulation variable "' + variableId + '" not defined' );
                }

                this.variables[ variableId ].min = this.variables[ variableId ].hasOwnProperty( 'min' ) ?
                    math.unit( this.variables[ variableId ].min ) : null;

                this.variables[ variableId ].max = this.variables[ variableId ].hasOwnProperty( 'max' ) ?
                    math.unit( this.variables[ variableId ].max ) : null;
            }
        } else {
            this.variables = {};
        }
    };

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

    mw.calculators.objectClasses.DrugPopulation.prototype.getCalculationData = function() {
        var inputData = new mw.calculators.objectClasses.CalculationData();

        for( var variableId in this.variables ) {
            inputData.variables.required.push( variableId );
        }

        return inputData;
    };

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

        for( var variableId in this.variables ) {
            if( !dataValues.hasOwnProperty( variableId ) ) {
                return -1;
            }

            if( this.variables[ variableId ].min &&
                ( !dataValues[ variableId ] ||
                    !math.largerEq( dataValues[ variableId ], this.variables[ variableId ].min ) ) ) {
                return -1;
            }

            if( this.variables[ variableId ].max &&
                ( !dataValues[ variableId ] ||
                    !math.smallerEq( dataValues[ variableId ], this.variables[ variableId ].max ) ) ) {
                return -1;
            }
        }

        // If the data matches the population definition, the score corresponds to the number of variables in the
        // 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() {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
    };



    /**
     * DrugRoute
     */
    mw.calculators.drugRoutes = {};

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

        for( var drugRouteId in drugRoutes ) {
            mw.calculators.drugRoutes[ drugRouteId ] = drugRoutes[ drugRouteId ];
        }
    };

    mw.calculators.getDrugRoute = function( drugRouteId ) {
        if( mw.calculators.drugRoutes.hasOwnProperty( drugRouteId ) ) {
            return mw.calculators.drugRoutes[ drugRouteId ];
        } else {
            return null;
        }
    };

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

        this.abbreviation = this.abbreviation ? this.abbreviation : this.name;
    };

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

    mw.calculators.objectClasses.DrugRoute.prototype.getProperties = function() {
        return {
            required: [
                'id',
                'name'
            ],
            optional: [
                'abbreviation',
                'default'
            ]
        };
    };

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







    /**
     * DrugIndication
     */
    mw.calculators.drugIndications = {};

    mw.calculators.addDrugIndications = function( drugIndicationData ) {
        var drugIndications = mw.calculators.createCalculatorObjects( 'DrugIndication', drugIndicationData );

        for( var drugIndicationId in drugIndications ) {
            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
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.DrugIndication}
     * @constructor
     */
    mw.calculators.objectClasses.DrugIndication = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
    };

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

    mw.calculators.objectClasses.DrugIndication.prototype.getProperties = function() {
        return {
            required: [
                'id',
                'name'
            ],
            optional: [
                'abbreviation',
                'default',
                'searchData'
            ]
        };
    };

    mw.calculators.objectClasses.DrugIndication.prototype.getSearchString = function() {
        var searchString = this.name;

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

        return searchString.trim();
    };

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





    /**
     * Drug
     */
    mw.calculators.drugs = {};

    mw.calculators.addDrugs = function( drugData ) {
        var drugs = mw.calculators.createCalculatorObjects( 'Drug', drugData );

        for( var drugId in drugs ) {
            mw.calculators.drugs[ drugId ] = drugs[ drugId ];
        }
    };

    mw.calculators.addDrugDosages = function( drugId, drugDosageData ) {
        var drug = mw.calculators.getDrug( drugId );

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

        drug.addDosages( drugDosageData );
    };

    mw.calculators.getDrug = function( drugId ) {
        if( mw.calculators.drugs.hasOwnProperty( drugId ) ) {
            return mw.calculators.drugs[ drugId ];
        } else {
            return null;
        }
    };



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

        if( !this.color ) {
            this.color = mw.calculators.getOptionValue( 'defaultDrugColor' );
        }

        var color = mw.calculators.getDrugColor( this.color );

        if( !color ) {
            throw new Error( 'Invalid drug color "' + this.color + '" for drug "' + this.id + '"' );
        }

        this.color = color;

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

            this.preparations = [];

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

        if( this.dosages ) {
            var dosageData = this.dosages;

            this.dosages = [];

            this.addDosages( dosageData );
        } else {
            this.dosages = [];
        }

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

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

    mw.calculators.objectClasses.Drug.prototype.addDosages = function( dosageData ) {
        var dosages = mw.calculators.createCalculatorObjects( 'DrugDosage', dosageData );

        for( var dosageId in dosages ) {
            dosages[ dosageId ].id = this.dosages.length;

            this.dosages.push( dosages[ dosageId ] );
        }
    };

    mw.calculators.objectClasses.Drug.prototype.addPreparations = function( preparationData ) {
        var preparations = mw.calculators.createCalculatorObjects( 'DrugPreparation', preparationData );

        for( var preparationId in preparations ) {
            preparations[ preparationId ].id = this.preparations.length;

            this.preparations.push( preparations[ preparationId ] );
        }
    };

    mw.calculators.objectClasses.Drug.prototype.getIndications = function() {
        var indications = [];

        for( var iDosage in this.dosages ) {
            if( this.dosages[ iDosage ].indication ) {
                indications.push( this.dosages[ iDosage ].indication );
            }
        }

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

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

    mw.calculators.objectClasses.Drug.prototype.getRoutes = function( indicationId ) {
        var routes = [];

        for( var iDosage in this.dosages ) {
            if( this.dosages[ iDosage ].routes.length &&
                ( !indicationId || ( this.dosages[ iDosage ].indication && this.dosages[ iDosage ].indication.id === indicationId ) ) ) {
                for( var iRoute in this.dosages[ iDosage ].routes ) {
                    routes.push( this.dosages[ iDosage ].routes[ iRoute ] );
                }
            }
        }

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

    mw.calculators.objectClasses.Drug.prototype.getPreparations = function( excludeDilutionRequired ) {
        var preparations = this.preparations.filter( mw.calculators.uniqueValues );

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

        return preparations;
    };

    mw.calculators.objectClasses.Drug.prototype.getProperties = function() {
        return {
            required: [
                'id',
                'name'
            ],
            optional: [
                'color',
                'description',
                'dosages',
                'formula',
                'preparations',
                'references',
                'searchData',
                'tradeNames'
            ]
        };
    };





    /**
     * DrugPreparation
     */
    mw.calculators.addDrugPreparations = function( drugId, drugPreparationData ) {
        var drug = mw.calculators.getDrug( drugId );

        if( !drug ) {
            throw new Error( 'DrugPreparation references drug "' + drugId + '" which is not defined' );
        }

        drug.addPreparations( drugPreparationData );
    };



    /**
     * Class DrugPreparation
     * @param {Object} propertyValues
     * @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 );


        this.concentration = this.concentration.replace( 'mcg', 'ug' );

        this.concentration = math.unit( this.concentration );
    };

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

    mw.calculators.objectClasses.DrugPreparation.prototype.getVolumeUnits = function() {
        // 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() {
        return mw.calculators.getValueString( this.concentration );
    };





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

        var drugIndication = mw.calculators.getDrugIndication( this.indication );

        if( !drugIndication ) {
            throw new Error( 'Invalid indication "' + this.indication + '" for drug dosage' );
        }

        this.indication = drugIndication;

        this.population = this.population ? this.population : mw.calculators.getOptionValue( 'defaultDrugPopulation' );

        var drugPopulation = mw.calculators.getDrugPopulation( this.population );

        if( !drugPopulation ) {
            throw new Error( 'Invalid population "' + this.population + '" for drug dosage' );
        }

        this.population = drugPopulation;

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

        this.routes = this.routes ? this.routes : [ mw.calculators.getOptionValue( 'defaultDrugRoute' ) ];

        if( !Array.isArray( this.routes ) ) {
            this.routes = [ this.routes ];
        }

        drugRoutes = [];

        for( var iRoute in this.routes ) {
            var drugRouteId = this.routes[ iRoute ];
            var drugRoute = mw.calculators.getDrugRoute( drugRouteId );

            if( !drugRoute ) {
                throw new Error( 'Invalid route "' + drugRouteId + '" for drug dosage' );
            }

            drugRoutes[ iRoute ] = drugRoute;
        }

        this.routes = drugRoutes;

        // Add the dose objects to the drug
        var drugDoseData = this.dose;
        this.dose = [];

        this.addDoses( drugDoseData );
    };

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

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

        var doses = mw.calculators.createCalculatorObjects( 'DrugDose', drugDoseData );

        for( var doseId in doses ) {
            doses[ doseId ].id = this.dose.length;

            this.dose.push( doses[ doseId ] );
        }
    };

    mw.calculators.objectClasses.DrugDosage.prototype.getCalculationData = function() {
        var inputData = new mw.calculators.objectClasses.CalculationData();

        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() {
        return {
            required: [
                'id'
            ],
            optional: [
                'description',
                'dose',
                'indication',
                'population',
                'routes',
                'references'
            ]
        };
    };

    mw.calculators.objectClasses.DrugDosage.prototype.getRouteString = function() {
        var routeString = '';

        for( var iRoute in this.routes ) {
            routeString += routeString ? '/' : '';
            routeString += this.routes[ iRoute ].abbreviation;
        }

        return routeString;
    };

    mw.calculators.objectClasses.DrugDosage.prototype.hasInfo = function() {
        return this.description;
    };





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

        if( this.weightCalculation ) {
            var weightCalculationIds = this.weightCalculation;

            // weightCalculation property will contain references to the actual objects, so reinitialize
            this.weightCalculation = [];

            if( !Array.isArray( weightCalculationIds ) ) {
                weightCalculationIds = [ weightCalculationIds ];
            }

            for( var iWeightCalculation in weightCalculationIds ) {
                var weightCalculationId = weightCalculationIds[ iWeightCalculation ];
                var weightCalculation = mw.calculators.getCalculation( weightCalculationId );

                if( !weightCalculation ) {
                    throw new Error( 'Drug dose references weight calculation "' + weightCalculationId + '" which is not defined' );
                }

                this.weightCalculation.push( weightCalculation );
            }
        } else {
            this.weightCalculation = [];
        }

        var mathProperties = this.getMathProperties();
        var isWeightDependent = false;

        for( var iMathProperty in mathProperties ) {
            var mathProperty = mathProperties[ iMathProperty ];

            if( this[ mathProperty ] ) {
                // TODO consider making a UnitsBase.weight.fromString()
                this[ mathProperty ] = this[ mathProperty ].replace( 'kg', 'kgwt' );
                this[ mathProperty ] = this[ mathProperty ].replace( 'mcg', 'ug' );

                this[ mathProperty ] = math.unit( this[ mathProperty ] );

                if( mw.calculators.isValueDependent( this[ mathProperty ], 'weight' ) ) {
                    isWeightDependent = true;
                }
            } else {
                this[ mathProperty ] = null;
            }
        }

        if( isWeightDependent ) {
            // 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.DrugDose.prototype.getAdministration = function() {
        var administration = '';

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

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

        return administration;
    };

    mw.calculators.objectClasses.DrugDose.prototype.getCalculationData = function() {
        var calculationData = new mw.calculators.objectClasses.CalculationData();

        for( var iWeightCalculation in this.weightCalculation ) {
            calculationData.calculations.optional.push( this.weightCalculation[ iWeightCalculation ].id );
        }

        return calculationData;
    };

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

    mw.calculators.objectClasses.DrugDose.prototype.getProperties = function() {
        return {
            required: [
                'id'
            ],
            optional: [
                'absoluteMax',
                'absoluteMin',
                'dose',
                'duration',
                'frequency',
                'min',
                'max',
                'name',
                'text',
                'weightCalculation'
            ]
        };
    };

}() );