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

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


     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' ) {
            return value && value.formatUnits().match( /\/[\s(]*?kg/ );
        } else {
            throw new Error( 'Dependence "' + variableId + '" not supported by isValueDependent' );
        }
    };


     var VALID_TYPES = [
     /**
         TYPE_NUMBER,
    * Define units
        TYPE_STRING
    */
    ];
    mw.calculators.addUnitsBases( {
         concentration: {
            toString: function( units ) {
                units = units.replace( ' pct', '%' );


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


         return null;
    mw.calculators.addUnits( {
     };
         pct: {
            baseName: 'concentration',
            definition: '10 mg/mL'
        },
        vial: {
            basename: 'VOLUME'
        }
     } );




    mw.calculators = {
        calculators: {},
        calculations: {},
        objectClasses: {},
        units: {},
        unitsBases: {},
        variables: {},
        addCalculations: function( calculationData, className ) {
            className = className ? className : DEFAULT_CALCULATION_CLASS;


            var calculations = mw.calculators.createCalculatorObjects( className, calculationData );
    /**
    * DrugColor
    */
    mw.calculators.drugColors = {};


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


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


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


                mw.calculators.calculations[ calculationId ].recalculate();
    /**
             }
    * Class DrugColor
        },
    * @param {Object} propertyValues
        addCalculators: function( moduleId, calculatorData, className ) {
    * @returns {mw.calculators.objectClasses.DrugColor}
             className = className ? className : DEFAULT_CALCULATOR_CLASS;
    * @constructor
    */
    mw.calculators.objectClasses.DrugColor = function( propertyValues ) {
        var properties = {
             required: [
                'id'
            ],
            optional: [
                'parentColor',
                'primaryColor',
                'highlightColor',
                'striped'
             ]
        };


            for( var calculatorId in calculatorData ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
                calculatorData[ calculatorId ].module = moduleId;
            }


             var calculators = mw.calculators.createCalculatorObjects( className, calculatorData );
        if( !this.primaryColor && !this.parentColor ) {
             throw new Error( 'Drug color "' + this.id + '" must define either a primary color or a parent color.' );
        }
    };


            if( !mw.calculators.calculators.hasOwnProperty( moduleId ) ) {
    mw.calculators.objectClasses.DrugColor.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                mw.calculators.calculators[ moduleId ] = {};
            }


            for( var calculatorId in calculators ) {
    mw.calculators.objectClasses.DrugColor.prototype.getParentDrugColor = function() {
                mw.calculators.calculators[ moduleId ][ calculatorId ] = calculators[ calculatorId ];
        if( !this.parentColor ) {
            return null;
        }


                mw.calculators.calculators[ moduleId ][ calculatorId ].render();
         var parentDrugColor = mw.calculators.getDrugColor( this.parentColor );
            }
         },
        addUnitsBases: function( unitsBaseData ) {
            var unitsBases = mw.calculators.createCalculatorObjects( 'UnitsBase', unitsBaseData );


            for( var unitsBaseId in unitsBases ) {
        if( !parentDrugColor ) {
                mw.calculators.unitsBases[ unitsBaseId ] = unitsBases[ unitsBaseId ];
             throw new Error( 'Parent drug color "' + this.parentColor + '" not found for drug color "' + this.id + '"' );
             }
        }
        },
        addUnits: function( unitsData ) {
            var units = mw.calculators.createCalculatorObjects( 'Units', unitsData );


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


                try {
    mw.calculators.objectClasses.DrugColor.prototype.getHighlightColor = function() {
                    math.createUnit( unitsId, {
        if( this.highlightColor ) {
                        aliases: units[ unitsId ].aliases,
            return this.highlightColor;
                        baseName: units[ unitsId ].baseName,
        } else if( this.parentColor ) {
                        definition: units[ unitsId ].definition,
            return this.getParentDrugColor().getHighlightColor();
                        prefixes: units[ unitsId ].prefixes,
        }
                        offset: units[ unitsId ].offset,
    };
                    } );
                } catch( e ) {
                    console.warn( e.message );
                }


                mw.calculators.units[ units ] = units[ unitsId ];
    mw.calculators.objectClasses.DrugColor.prototype.getPrimaryColor = function() {
             }
        if( this.primaryColor ) {
         },
             return this.primaryColor;
        addVariables: function( variableData ) {
         } else if( this.parentColor ) {
             var variables = mw.calculators.createCalculatorObjects( 'Variable', variableData );
             return this.getParentDrugColor().getPrimaryColor();
        }
    };


             for( var varId in variables ) {
    mw.calculators.objectClasses.DrugColor.prototype.isStriped = function() {
                var variable = variables[ varId ];
        if( this.striped !== null ) {
             return this.striped;
        } else if( this.parentColor ) {
            return this.getParentDrugColor().isStriped();
        }
    };


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


                if( cookieValue ) {
                    variable.setValue( cookieValue );
                }


                mw.calculators.variables[ varId ] = variable;
            }
        },
        createCalculatorObjects: function( className, objectData ) {
            if( !mw.calculators.objectClasses.hasOwnProperty( className ) ) {
                throw new Error( 'Invalid class name "' + className + '"' );
            }


            var objects = {};


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


                if( typeof objectId === 'string' ) {
    mw.calculators.drugPopulations = {};
                    propertyValues.id = objectId;
                }


                objects[ objectId ] = new mw.calculators.objectClasses[ className ]( propertyValues );
    mw.calculators.addDrugPopulations = function( drugPopulationData ) {
            }
        var drugPopulations = mw.calculators.createCalculatorObjects( 'DrugPopulation', drugPopulationData );


            return objects;
         for( var drugPopulationId in drugPopulations ) {
         },
             mw.calculators.drugPopulations[ drugPopulationId ] = drugPopulations[ drugPopulationId ];
        createInputGroup: function( variableIds ) {
        }
             var $form = $( '<form>', {
    };


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


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


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


                if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
    /**
                    throw new Error( 'Invalid variable name "' + variableId + '"' );
    * 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'
            ]
        };


                $formRow.append( mw.calculators.variables[ variableId ].createInput() );
        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
            }


            return $form.append( $formRow );
         if( this.variables ) {
         },
             for( var variableId in this.variables ) {
        getCookieKey: function( variableId ) {
                if( !mw.calculators.getVariable( variableId ) ) {
             return 'calculators-var-' + variableId;
                    throw new Error( 'DrugPopulation variable "' + variableId + '" not defined' );
        },
                }
        getCookieValue: function( varId ) {
            var cookieValue = mw.cookie.get( mw.calculators.getCookieKey( varId ) );


            if( !cookieValue ) {
                this.variables[ variableId ].min = this.variables[ variableId ].hasOwnProperty( 'min' ) ?
                return null;
                    math.unit( this.variables[ variableId ].min ) : null;
            }


            return cookieValue;
                 this.variables[ variableId ].max = this.variables[ variableId ].hasOwnProperty( 'max' ) ?
        },
                    math.unit( this.variables[ variableId ].max ) : null;
        getCalculation: function( calculationId ) {
            if( mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
                 return mw.calculators.calculations[ calculationId ];
            } else {
                return null;
            }
        },
        getCalculator: function( moduleId, calculatorId ) {
            if( mw.calculators.calculators.hasOwnProperty( moduleId ) &&
                mw.calculators.calculators[ moduleId ].hasOwnProperty( calculatorId ) ) {
                return mw.calculators.calculators[ moduleId ][ calculatorId ];
            } else {
                return null;
            }
        },
        getUnitsString: function( value ) {
            if( typeof value !== 'object' ) {
                return null;
             }
             }
        } else {
            this.variables = {};
        }
    };


            var unitsString = value.formatUnits();
    mw.calculators.objectClasses.DrugPopulation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );


            var reDenominator = /\/\s?\((.*)\)/;
    mw.calculators.objectClasses.DrugPopulation.prototype.getCalculationData = function() {
            var denominatorMatches = unitsString.match( reDenominator );
        var inputData = new mw.calculators.objectClasses.CalculationData();


            if( denominatorMatches ) {
        for( var variableId in this.variables ) {
                var denominatorUnits = denominatorMatches[ 1 ];
            inputData.variables.required.push( variableId );
        }


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


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


            if( unitsBase ) {
        for( var variableId in this.variables ) {
                if( mw.calculators.unitsBases.hasOwnProperty( unitsBase ) &&
            if( !dataValues.hasOwnProperty( variableId ) ) {
                    typeof mw.calculators.unitsBases[ unitsBase ].toString === 'function' ) {
                 return -1;
                    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;
             if( this.variables[ variableId ].min &&
        },
                !math.largerEq( dataValues[ variableId ], this.variables[ variableId ].min ) ) {
        getValueString: function( value ) {
                 return -1;
            if( typeof value !== 'object' ) {
                 return null;
             }
             }


             var valueString = String( value.toNumber() );
             if( this.variables[ variableId ].max &&
 
                !math.smallerEq( dataValues[ variableId ], this.variables[ variableId ].max ) ) {
            if( value.formatUnits() ) {
                 return -1;
                 valueString += ' ' + mw.calculators.getUnitsString( value );
             }
             }
        }


            return valueString;
         // 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.
         getVariable: function( variableId ) {
        return Object.keys( this.variables ).length;
            if( mw.calculators.variables.hasOwnProperty( variableId ) ) {
    };
                return mw.calculators.variables[ variableId ];
            } else {
                return null;
            }
        },
        initialize: function() {
            math.config( {
                number: 'BigNumber'
            } );


            $( '.calculator' ).each( function() {
    mw.calculators.objectClasses.DrugPopulation.prototype.toString = function() {
                var gadgetModule = 'ext.gadget.calculator-' + $( this ).attr( 'data-module' );
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
    }


                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' );
        },
        setValue: function( variableId, value ) {
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return false;
            }


            if( mw.calculators.variables[ variableId ].setValue( value ) ) {
                mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
                    expires: COOKIE_EXPIRATION
                } );


                return true;
            }


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


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


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


                    this[ requiredProperty ] = propertyValues[ requiredProperty ];
        for( var drugIndicationId in drugIndications ) {
 
            mw.calculators.drugIndications[ drugIndicationId ] = drugIndications[ drugIndicationId ];
                    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.getDrugIndication = function( drugIndicationId ) {
         return {
         if( mw.calculators.drugIndications.hasOwnProperty( drugIndicationId ) ) {
            required: [],
             return mw.calculators.drugIndications[ drugIndicationId ];
            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 DrugIndication
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.UnitsBase}
     * @returns {mw.calculators.objectClasses.DrugIndication}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.UnitsBase = function( propertyValues ) {
     mw.calculators.objectClasses.DrugIndication = function( propertyValues ) {
         var properties = {
         var properties = {
             required: [
             required: [
                 'id'
                 'id',
                'name'
             ],
             ],
             optional: [
             optional: [
                 'toString'
                 'abbreviation'
             ]
             ]
         };
         };
Line 366: Line 279:
     };
     };


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




Line 372: Line 290:


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


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


     mw.calculators.objectClasses.Units.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
     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 );
        var calculationId = 'drugDosage-' + drugId;
        var calculation = mw.calculators.getCalculation( calculationId );
        if( !calculation ) {
            var calculationData = {};
            calculationData[ calculationId ] = {
                calculate: mw.calculators.objectClasses.DrugDosageCalculation.prototype.calculate,
                drug: drugId,
                type: 'drug'
            };
            mw.calculators.addCalculations( calculationData, 'DrugDosageCalculation' );
            calculation = mw.calculators.getCalculation( calculationId );
        }
        calculation.setDependencies();
    };
    mw.calculators.getDrug = function( drugId ) {
        if( mw.calculators.drugs.hasOwnProperty( drugId ) ) {
            return mw.calculators.drugs[ drugId ];
        } else {
            return null;
        }
    };






     /**
     /**
     * Class Variable
     * Class Drug
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.Variable}
     * @returns {mw.calculators.objectClasses.Drug}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.Variable = function( propertyValues ) {
     mw.calculators.objectClasses.Drug = function( propertyValues ) {
         var properties = {
         var properties = {
             required: [
             required: [
                 'id',
                 'id',
                 'name',
                 'name'
                'type'
             ],
             ],
             optional: [
             optional: [
                 'abbreviation',
                 'color'
                'defaultValue',
                'maxLength',
                'options',
                'units'
             ]
             ]
         };
         };
Line 423: Line 360:
         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );


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


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


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


         this.calculations = [];
         this.color = color;


         if( this.defaultValue ) {
         this.dosages = [];
            this.setValue( this.defaultValue );
         this.preparations = [];
         } else {
            this.value = null;
        }
     };
     };


     mw.calculators.objectClasses.Variable.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
     mw.calculators.objectClasses.Drug.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
 
    mw.calculators.objectClasses.Variable.prototype.addCalculation = function( calculationId ) {
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
            return;
        }
 
        this.calculations.push( calculationId );
    };
 
    mw.calculators.objectClasses.Variable.prototype.createInput = function( hideLabel ) {
        var variableId = this.id;
 
        var inputContainerAttribs = {
            class: 'form-group mb-0 calculator-container-input'
        };
 
        inputContainerAttribs.class = inputContainerAttribs.class + ' calculator-container-input-' + variableId;
 
        // Create the input container
        var $inputContainer = $( '<div>', inputContainerAttribs );


        // Set the input id
    mw.calculators.objectClasses.Drug.prototype.addDosages = function( drugDosageData ) {
         var inputId = 'calculator-input-' + variableId;
         var dosages = mw.calculators.createCalculatorObjects( 'DrugDosage', drugDosageData );


         // Initialize label attributes
         for( var dosageId in dosages ) {
        var labelAttributes = {
             dosages[ dosageId ].id = this.dosages.length;
             for: inputId,
            text: this.getLabelString()
        };


        if( hideLabel ) {
            this.dosages.push( dosages[ dosageId ] );
            labelAttributes.class = 'sr-only';
         }
         }
    };


        // Create the input label and append to the container
    mw.calculators.objectClasses.Drug.prototype.getIndications = function() {
        $inputContainer.append( $( '<label>', labelAttributes ) );
        var indications = [];


         if( this.type === TYPE_NUMBER ) {
         for( var iDosage in this.dosages ) {
             // Initialize the primary units variables (needed for handlers, even if doesn't have units)
             if( this.dosages[ iDosage ].indication ) {
            var unitsId = null;
                 indications.push( this.dosages[ iDosage ].indication );
            var $unitsContainer = null;
 
            // Initialize input options
            var inputAttributes = {
                id: inputId,
                class: 'form-control calculator-input-text',
                type: 'text',
                autocomplete: 'off',
                inputmode: 'decimal',
                value: this.isValueMathObject() ? this.value.toNumber() : this.value
            };
 
            // Configure additional options
            if( this.maxLength ) {
                 inputAttributes.maxlength = this.maxLength;
             }
             }
        }


            // Add the input id to the list of classes
         return indications.filter( mw.calculators.uniqueValues );
            inputAttributes.class = inputAttributes.class + ' ' + inputId;
    };
 
            // If the variable has units, create the units input
            if( this.hasUnits() ) {
                // Set the units id
                unitsId = inputId + '-units';
 
                var unitsValue = this.isValueMathObject() ? this.value.formatUnits() : null;
 
                // Create the units container
                $unitsContainer = $( '<div>', {
                    class: 'input-group-append'
                } );
 
                // Initialize the units input options
                var unitsInputAttributes = {
                    id: unitsId,
                    class: 'custom-select calculator-input-select'
                };
 
                unitsInputAttributes.class = unitsInputAttributes.class + ' ' + unitsId;
 
                var $unitsInput = $( '<select>', unitsInputAttributes )
                    .on( 'change', function() {
                        var newValue = $( '#' + inputId ).val() + ' ' + $( this ).val();
 
                        mw.calculators.setValue( variableId, newValue );
                    } );
 
                for( var iUnits in this.units ) {
                    var units = this.units[ iUnits ];
 
                    var unitsOptionAttributes = {
                        text: mw.calculators.getUnitsString( math.unit( '0 ' + units ) ),
                        value: units
                    };
 
                    if( units === unitsValue ) {
                        unitsOptionAttributes.selected = true;
                    }
 
                    $unitsInput.append( $( '<option>', unitsOptionAttributes ) );
                }
 
                $unitsContainer.append( $unitsInput );
            }
 
            // Create the input and add handlers
            var $input = $( '<input>', inputAttributes )
                .on( 'input', function() {
                    var newValue = $( this ).val();
 
                    if( unitsId ) {
                        newValue = newValue + ' ' + $( '#' + unitsId ).val();
                    }
 
                    mw.calculators.setValue( variableId, newValue );
                } );
 
            // Create the input group
            var $inputGroup = $( '<div>', {
                class: 'input-group'
            } ).append( $input );
 
            if( $unitsContainer ) {
                $inputGroup.append( $unitsContainer );
            }
 
            $inputContainer.append( $inputGroup );
         } else if( this.type === TYPE_STRING ) {
            if( this.hasOptions() ) {
                var selectAttributes = {
                    id: inputId,
                    class: 'custom-select calculator-input-select'
                };
 
                var $select = $( '<select>', selectAttributes )
                    .on( 'change', function() {
                        mw.calculators.setValue( variableId, $( this ).val() );
                    } );
 
                for( var optionId in this.options ) {
                    var displayText = this.options[ optionId ];


                    var optionAttributes = {
    mw.calculators.objectClasses.Drug.prototype.getPopulations = function( indicationId ) {
                        value: optionId,
        var populations = [];
                        text: displayText
                    };


                    if( optionId === this.value ) {
        for( var iDosage in this.dosages ) {
                        optionAttributes.selected = true;
            if( this.dosages[ iDosage ].population &&
                    }
                ( !indicationId || ( this.dosages[ iDosage ].indication && this.dosages[ iDosage ].indication.id === indicationId ) ) ) {
 
                 populations.push( this.dosages[ iDosage ].population );
                    $select.append( $( '<option>', optionAttributes ) );
                }
 
                 $inputContainer.append( $select );
             }
             }
         }
         }


         return $inputContainer;
         return populations.filter( mw.calculators.uniqueValues );
     };
     };


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


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


    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() {
 
         if( !this.value ||
    /**
            ( this.isValueMathObject() && !this.value.toNumber() ) ) {
    * DrugPreparation
             return false;
    */
     mw.calculators.addDrugPreparations = function( drugId, drugPreparationData ) {
         if( !mw.calculators.getDrug( drugId ) ) {
             throw new Error( 'DrugPreparation references drug "' + drugId + '" which is not defined' );
         }
         }


         return true;
         for( var drugPreparationId in drugPreparationData ) {
    };
             drugPreparationData[ drugPreparationId ].drug = drugId;
 
    mw.calculators.objectClasses.Variable.prototype.isValueMathObject = function() {
        return mw.calculators.isValueMathObject( this.value );
    };
 
    mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
        if( this.type === TYPE_NUMBER ) {
            if( typeof value !== 'object' ) {
                value = math.unit( value );
            }
 
             if( this.hasUnits() ) {
                var valueUnits = value.formatUnits();
 
                if( !valueUnits ) {
                    throw new Error( 'Could not set value for "' + this.id + '": Value must define units' );
                } else if( this.units.indexOf( valueUnits ) === -1 ) {
                    throw new Error( 'Could not set value for "' + this.id + '": Units "' + valueUnits + '" are not valid for this variable' );
                }
            }
        } else if( this.hasOptions() ) {
            if( !this.options.hasOwnProperty( value ) ) {
                throw new Error( 'Could not set value "' + value + '" for "' + this.id + '": Value must define be one of: ' + Object.keys( this.options ).join( ', ' ) );
            }
         }
         }


         this.value = value;
         var drugPreparations = mw.calculators.createCalculatorObjects( 'DrugPreparation', drugPreparationData );


         for( var iCalculation in this.calculations ) {
         for( var drugPreparationId in drugPreparations ) {
             var calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );
             mw.calculators.drugs[ drugId ].preparations[ drugPreparationId ] = drugPreparations[ drugPreparationId ];
 
            if( calculation ) {
                calculation.render();
            }
         }
         }
        return true;
     };
     };


Line 677: Line 443:


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


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


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


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


        this.calculations.push( calculationId );
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.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 {
    * Class DrugDosage
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.DrugDosage}
    * @constructor
    */
    mw.calculators.objectClasses.DrugDosage = function( propertyValues ) {
         var properties = {
             required: [
             required: [
                'dose',
                 'id',
                 'id',
                 'calculate'
                 'indication'
             ],
             ],
             optional: [
             optional: [
                 'data',
                 'population'
                'description',
                'onRender',
                'onRendered',
                'references',
                'type'
             ]
             ]
         };
         };
    };


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


    mw.calculators.objectClasses.AbstractCalculation.prototype.hasInfo = function() {
        var drugIndication = mw.calculators.getDrugIndication( this.indication );
        return false;
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.hasValue = function() {
         if( !drugIndication ) {
         if( !this.value ||
             throw new Error( 'Invalid indication "' + this.indication + '" for drug dosage' );
             ( this.isValueMathObject() && !this.value.toNumber() ) ) {
            return false;
         }
         }


         return true;
         this.indication = drugIndication;
    };


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


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


         var data = {};
         if( !drugPopulation ) {
        var missingRequiredData = '';
            throw new Error( 'Invalid population "' + this.population + '" for drug dosage' );
        var calculationId, calculation, variableId, variable;
 
        for( var iRequiredCalculation in calculationData.calculations.required ) {
            calculationId = calculationData.calculations.required[ iRequiredCalculation ];
            calculation = mw.calculators.getCalculation( calculationId );
 
            if( !calculation ) {
                throw new Error( 'Invalid required calculation "' + calculationId + '" for calculation "' + this.id + '"' );
            } else if( !calculation.hasValue() ) {
                if( missingRequiredData ) {
                    missingRequiredData = missingRequiredData + ', ';
                }
 
                missingRequiredData = missingRequiredData + calculation.getLabelString();
            } else {
                data[ calculationId ] = calculation.value;
            }
         }
         }


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


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


                missingRequiredData = missingRequiredData + variable.getLabelString();
        this.addDoses( drugDoseData );
            } else {
    };
                data[ variableId ] = variable.value;
            }
        }


        if( missingRequiredData ) {
    mw.calculators.objectClasses.DrugDosage.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
            this.message = missingRequiredData + ' required';


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


         for( var iOptionalCalculation in calculationData.calculations.optional ) {
         var doses = mw.calculators.createCalculatorObjects( 'DrugDose', drugDoseData );
            calculationId = calculationData.calculations.optional[ iOptionalCalculation ];
            calculation = mw.calculators.getCalculation( calculationId );


            if( !calculation ) {
        for( var doseId in doses ) {
                throw new Error( 'Invalid optional calculation "' + calculationId + '" for calculation "' + this.id + '"' );
            doses[ doseId ].id = this.dose.length;
            }


             data[ calculationId ] = calculation.hasValue() ? calculation.value : null;
             this.dose.push( doses[ doseId ] );
         }
         }
    };


        for( var iOptionalVariable in calculationData.variables.optional ) {
    mw.calculators.objectClasses.DrugDosage.prototype.getCalculationData = function() {
            variableId = calculationData.variables.optional[ iOptionalVariable ];
        var inputData = new mw.calculators.objectClasses.CalculationData();
            variable = mw.calculators.getVariable( variableId );


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


             data[ variableId ] = variable.hasValue() ? variable.value : null;
        for( var iDose in this.dose ) {
             inputData = inputData.merge( this.dose[ iDose ].getCalculationData() );
         }
         }


         return data;
         return inputData;
     };
     };


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


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


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


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


        this.message = null;
    /**
         this.value = null;
    * 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 );


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


    mw.calculators.objectClasses.AbstractCalculation.prototype.recalculate = function() {
        for( var iMathProperty in mathProperties ) {
        this.message = '';
            var mathProperty = mathProperties[ iMathProperty ];
        this.value = null;


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


        if( data === false ) {
                this[ mathProperty ] = math.unit( this[ mathProperty ] )
             return false;
            } else {
                this[ mathProperty ] = null;
             }
         }
         }


         try {
         if( this.weightCalculation ) {
             var value = this.calculate( data );
             var weightCalculation = mw.calculators.getCalculation( this.weightCalculation );
 
            if( this.type === TYPE_NUMBER && !isNaN( value ) ) {
                if( this.units ) {
                    value = value + ' ' + this.units;
                }


                this.value = math.unit( value );
            if( !weightCalculation ) {
            } else {
                 throw new Error( 'Drug dose references weight calculation "' + this.weightCalculation + '" which is not defined' );
                 this.value = value;
             }
             }


             for( var iCalculation in this.calculations ) {
             this.weightCalculation = weightCalculation;
                calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );
 
                if( calculation ) {
                    calculation.render();
                }
            }
        } catch( e ) {
            this.message = e.message;
            this.value = null;
         }
         }
        return true;
     };
     };


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


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


    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
        var mathProperties = this.getMathProperties();
        this.recalculate();


         if( typeof this.onRender === 'function' ) {
         // Look at dose properties to identify any variable dependence (e.g. weight-dependence)
             this.onRender();
        for( var iMathProperty in mathProperties ) {
        }
             var mathProperty = mathProperties[ iMathProperty ];


        this.doRender();
            var dosePropertyValue = this[ mathProperty ];


        if( typeof this.onRendered === 'function' ) {
            // For now, this only supports weight dependence, unclear if it will need to be more generalizable in the future
            this.onRendered();
            if( mw.calculators.isValueDependent( dosePropertyValue, 'weight' ) &&
                calculationData.variables.optional.indexOf( 'weight' ) === -1 ) {
                calculationData.variables.optional.push( 'weight' );
            }
         }
         }
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.setDependencies = function() {
        if( this.weightCalculation ) {
        var calculationData = this.getCalculationData();
            calculationData.calculations.optional.push( this.weightCalculation.id );
        }


         var calculationIds = calculationData.calculations.required.concat( calculationData.calculations.optional );
         return calculationData;
    };


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


            if( !mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
    mw.calculators.objectClasses.DrugDose.prototype.getProperties = function() {
                 throw new Error('Calculation "' + calculationId + '" does not exist for calculation "' + this.id + '"');
        return {
            }
            required: [
                'id'
            ],
            optional: [
                'absoluteMin',
                'absoluteMax',
                'dose',
                'min',
                'max',
                 'name',
                'route',
                'weightCalculation'
            ]
        };
    };


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


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


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


            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
    /**
                throw new Error('Variable "' + variableId + '" does not exist for calculation "' + this.id + '"');
    * Class DrugDosageCalculation
            }
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.DrugDosageCalculation}
    * @constructor
    */
    mw.calculators.objectClasses.DrugDosageCalculation = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


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


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


    mw.calculators.objectClasses.DrugDosageCalculation.prototype.calculate = function( data ) {
        var value = {
            population: null,
            dose: []
        };


    mw.calculators.objectClasses.AbstractCalculation.prototype.doRender = function() {};
        // Determine which dosage to use
        var populationScores = [];


        for( var iDosage in data.drug.dosages ) {
            var drugDosage = data.drug.dosages[ iDosage ];


            // If the indication does not match, set the score to -1
            var populationScore = ( drugDosage.indication.id === data.indication.id ) ?
                drugDosage.population.getCalculationDataScore( data ) : -1;


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


         var dataTypes = this.getDataTypes();
         var maxPopulationScore = Math.max.apply( null, populationScores );


         for( var iDataType in dataTypes ) {
         if( maxPopulationScore < 0 ) {
            var dataType = dataTypes[ iDataType ];
             return value;
 
            if( !this[ dataType ] ) {
                this[ dataType ] = {
                    optional: [],
                    required: []
                };
             } else {
                this[ dataType ].optional = this[ dataType ].hasOwnProperty( 'optional' ) ? this[ dataType ].optional : [];
                this[ dataType ].required = this[ dataType ].hasOwnProperty( 'required' ) ? this[ dataType ].required : [];
            }
         }
         }
    };


    mw.calculators.objectClasses.CalculationData.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        // If there is more than one dosage with the same score, take the first.
        // This allows the data editor to decide which is most important.
        var dosageId = populationScores.indexOf( maxPopulationScore );


    mw.calculators.objectClasses.CalculationData.prototype.getDataTypes = function() {
        var dosage = data.drug.dosages[ dosageId ];
        return [
            'calculations',
            'variables'
        ];
    };


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


        // A dosage may contain multiple doses (e.g. induction and maintenance)
        for( var iDose in dosage.dose ) {
            var dose = dosage.dose[ iDose ];
            var mathProperties = dose.getMathProperties();


            // Initialize value properties for dose
            value.dose[ iDose ] = {
                massPerWeight: {},
                mass: {},
                name: dose.name,
                volume: {},
                weightCalculation: dose.weightCalculation ? dose.weightCalculation : null
            };


    mw.calculators.objectClasses.CalculationData.prototype.merge = function() {
            var weightValue = dose.weightCalculation ? dose.weightCalculation.value : data.weight;
        var mergedData = new mw.calculators.objectClasses.CalculationData();


        var data = [ this ].concat( Array.prototype.slice.call( arguments ) );
            for( var iMathProperty in mathProperties ) {
                var mathProperty = mathProperties[ iMathProperty ];


        var dataTypes = this.getDataTypes();
                var doseValue = dose[ mathProperty ];


        for( var iData in data ) {
                if( doseValue ) {
            for( var iDataType in dataTypes ) {
                    if( mw.calculators.isValueDependent( doseValue, 'weight' ) ) {
                var dataType = dataTypes[ iDataType ];
                        value.dose[ iDose ].massPerWeight[ mathProperty ] = doseValue;


                mergedData[ dataType ].required = mergedData[ dataType ].required
                        // For whatever reason math.format will simplify the units, but math.formatUnits will not
                    .concat( data[ iData ][ dataType ].required )
                        // as a hack, we recreate a new unit value with the correct formatting of the result
                    .filter( mw.calculators.uniqueValues );
                        value.dose[ iDose ].mass[ mathProperty ] = weightValue ? math.unit( math.multiply( doseValue, weightValue ).format() ) : null;
                        console.log(doseValue.format());
                        console.log(weightValue.format());
                    } else {
                        value.dose[ iDose ].mass[ mathProperty ] = doseValue;
                    }


                mergedData[ dataType ].optional = mergedData[ dataType ].optional
                    if( data.preparation && value.dose[ iDose ].mass[ mathProperty ] ) {
                    .concat( data[ iData ][ dataType ].optional )
                        // Same hack as above to get units to simplify correctly
                    .filter( mw.calculators.uniqueValues );
                        value.dose[ iDose ].volume[ mathProperty ] = math.unit( math.multiply( value.dose[ iDose ].mass[ mathProperty ], math.divide( 1, data.preparation.concentration ) ).format() );
                    }
                }
             }
             }
         }
         }


         return mergedData;
         return value;
     };
     };


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


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


        $calculationContainer.empty();


        var labelHtml = this.getLabelHtml();
        var labelAttributes = {};
        var labelCss = {
            'background-color': this.drug.color.getPrimaryColor()
        };


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


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


    mw.calculators.objectClasses.SimpleCalculation.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculation.prototype );
            labelHtml += $( '<span>', {
                class: 'calculator-calculation-column-label-info'
            } ).append( $infoButton )[ 0 ].outerHTML;
        }


        var indicationHtml = '';


    mw.calculators.objectClasses.SimpleCalculation.prototype.hasInfo = function() {
        var indications = this.drug.getIndications();
        return this.description || this.formula || this.references.length;
    };


    mw.calculators.objectClasses.SimpleCalculation.prototype.getLabelHtml = function() {
        if( indications.length > 1 ) {
        var labelHtml = this.getLabelString();
            indicationHtml += mw.calculators.getVariable( this.getVariableIds().indication  ).createInput( true );
        } else {
            indicationHtml += String( indications[ 0 ] );
        }


         if( this.link ) {
        var dosageHtml = '';
             var href = this.link;
console.log( this );
         if( this.value.population && this.value.population.id !== DEFAULT_DRUG_POPULATION ) {
             dosageHtml += String( this.value.population ) + '<br />';
        }


            // Detect internal links (this isn't great)
        for( var iDose in this.value.dose ) {
             var matches = href.match( /\[\[(.*?)\]\]/ );
             var doseValue = this.value.dose[ iDose ];


             if( matches ) {
             if( doseValue.name ) {
                 href = mw.util.getUrl( matches[ 1 ] );
                 dosageHtml += doseValue.name + '<br />';
             }
             }


             labelHtml = $( '<a>', {
             if( !$.isEmptyObject( doseValue.massPerWeight ) ) {
                 href: href,
                if( doseValue.massPerWeight.hasOwnProperty( 'dose' ) ) {
                text: labelHtml
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.dose );
            } )[ 0 ].outerHTML;
                 } else if( doseValue.massPerWeight.hasOwnProperty( 'min' ) &&
        }
                    doseValue.massPerWeight.hasOwnProperty( 'max' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.min );
                    dosageHtml += '-';
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.max );
                }


        return labelHtml;
                if( doseValue.weightCalculation ) {
    };
                    dosageHtml += ' (' + doseValue.weightCalculation.getLabelString() + ')';
                }


    mw.calculators.objectClasses.SimpleCalculation.prototype.getLabelString = function() {
                dosageHtml += '<br />';
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
            }
    };


    mw.calculators.objectClasses.SimpleCalculation.prototype.getProperties = function() {
            if( !$.isEmptyObject( doseValue.mass ) ) {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();
                if( doseValue.mass.hasOwnProperty( 'dose' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.mass.dose );
                } else if( doseValue.mass.hasOwnProperty( 'min' ) &&
                    doseValue.mass.hasOwnProperty( 'max' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.mass.min );
                    dosageHtml += '-';
                    dosageHtml += mw.calculators.getValueString( doseValue.mass.max );
                }


        return this.mergeProperties( inheritedProperties, {
                 dosageHtml += '<br />';
            required: [
             }
                 'name'
             ],
            optional: [
                'abbreviation',
                'digits',
                'formula',
                'link',
                'units'
            ]
        } );
    };


    mw.calculators.objectClasses.SimpleCalculation.prototype.getValueString = function() {
            if( !$.isEmptyObject( doseValue.volume ) ) {
        if( this.message ) {
                if( doseValue.volume.hasOwnProperty( 'dose' ) ) {
            return this.message;
                    dosageHtml += mw.calculators.getValueString( doseValue.volume.dose );
        } else if( typeof this.value === 'object' && this.value.hasOwnProperty( 'value' ) ) {
                } else if( doseValue.volume.hasOwnProperty( 'min' ) &&
            // format() will convert the value to the most visually appealing units (e.g. 5200 mL becomes 5.2 L)
                    doseValue.volume.hasOwnProperty( 'max' ) ) {
            // We then want to turn that back into a math object.
                    dosageHtml += mw.calculators.getValueString( doseValue.volume.min );
            var value = math.unit( this.value.format() );
                    dosageHtml += '-';
            var units = value.formatUnits();
                    dosageHtml += mw.calculators.getValueString( doseValue.volume.max );
            var number = value.toNumber();
                }
 
            var digits = ( this.value.formatUnits() === units && this.digits !== null ) ? this.digits : 1;
 
            var valueString = String( number.toFixed( digits ) );


            if( units ) {
                 dosageHtml += '<br />';
                 valueString = valueString + ' ' + mw.calculators.getUnitsString( value );
             }
             }


             return valueString;
             dosageHtml += '<br />';
        } else {
            return String( this.value );
         }
         }
    };


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


         if( !$calculationContainer.length ) {
         $calculationContainer
             return;
            .append(
        }
                $( '<th>', labelAttributes ).html( labelHtml ).css( labelCss ),
                $( '<td>' ).html( indicationHtml ),
                $( '<td>' ).html( dosageHtml )
             );


        var valueString = this.getValueString();


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


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


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


         var calculation = this;
         var calculation = this;
Line 1,114: Line 856:
             $( this ).empty();
             $( this ).empty();


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


            var $infoButton = null;


            if( calculation.hasInfo() ) {
                $infoButton = $( '<a>', {
                    'data-toggle': 'collapse',
                    href: '#' + calculation.getContainerClass() + '-info',
                    role: 'button',
                    'aria-expanded': 'false',
                    'aria-controls': calculation.getContainerClass() + '-info'
                } )
                    .append( $( '<i>', {
                        class: 'far fa-question-circle'
                    } ) );
            }
            var labelHtml = calculation.getLabelHtml();
            if( isTable ) {
                if( calculation.hasInfo() ) {
                    labelHtml += $( '<span>', {
                        class: 'calculator-calculation-column-label-info'
                    } ).append( $infoButton )[ 0 ].outerHTML;
                }
                $( this )
                    .append( $( '<th>', {
                        html: labelHtml
                    } ) )
                    .append( $( '<td>', {
                        class: 'calculator-calculation-column-value',
                        html: valueString
                    } ) );
            } else {
                $( this )
                    .append( labelHtml + $infoButton[ 0 ].outerHTML + ': ' + valueString );
            }


             if( calculation.hasInfo() ) {
             if( calculation.hasInfo() ) {
Line 1,193: Line 899:
                 }
                 }


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


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


            if( missingVariableInputs.length ) {
    mw.calculators.objectClasses.DrugDosageCalculation.prototype.getCalculationData = function() {
                var variablesContainerClass = 'calculator-calculation-variables ' + calculation.getContainerClass() + '-variables';
        var inputData = new mw.calculators.objectClasses.CalculationData();
                var inputGroup = mw.calculators.createInputGroup( missingVariableInputs );


                if( isTable ) {
        // Add variables created by this calculation
                    $variablesContainer = $( '<tr>' )
        var variableIds = this.getVariableIds();
                        .append( $( '<td>', {
 
                            class: variablesContainerClass,
        for( var variableType in variableIds ) {
                            colspan: 2
            inputData.variables.optional.push( variableIds[ variableType ] );
                        } ).append( inputGroup ) );
        }
 
        var dataTypes = inputData.getDataTypes();
 
        // Data is only actually required if it is required by every dosage for the drug.
        // Data marked as required by an individual dosage that does not appear in every
        // dosage will be converted to optional.
        var requiredInputData = new mw.calculators.objectClasses.CalculationData();
 
        // Need a way to tell the first iteration of the loop to initialize the required variables to a value that
        // is distinct from the empty array (populated across loop using array intersect, so could become [] and shouldn't
        // reinitialize).
        var initializeRequiredData = true;
 
        // Iterate through each dosage to determine variable dependency
        for( var iDosage in this.drug.dosages ) {
            var dosageInputData = this.drug.dosages[ iDosage ].getCalculationData();
 
            inputData = inputData.merge( dosageInputData );
 
            for( var iDataType in dataTypes ) {
                var dataType = dataTypes[ iDataType ];
 
                if( initializeRequiredData ) {
                    requiredInputData[ dataType ].required = inputData[ dataType ].required;
                 } else {
                 } else {
                     $variablesContainer = $( '<div>', {
                     // Data is only truly required if it is required by all dosage calculations, so use array intersection
                         class: variablesContainerClass
                    requiredInputData[ dataType ].required = requiredInputData[ dataType ].required.filter( function( index ) {
                     } ).append( inputGroup );
                         return dosageInputData[ dataType ].required.indexOf( index ) !== -1;
                     } );
                 }
                 }
            }


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


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


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


        data.drug = this.drug;


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


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


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


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


     mw.calculators.objectClasses.AbstractCalculator.prototype.getContainerClass = function() {
     mw.calculators.objectClasses.DrugDosageCalculation.prototype.getLabelHtml = function() {
         return 'calculator-' + this.module + '-' + this.id;
         var labelHtml = this.drug.name;
 
        var $label = $( '<a>', {
            href: mw.util.getUrl( this.drug.name ),
            text: labelHtml
        } );
 
        var highlightColor = this.drug.color.getHighlightColor();
 
        if( highlightColor ) {
            $label.css( 'background-color', highlightColor );
        }
 
        labelHtml = $label[ 0 ].outerHTML;
 
        return labelHtml;
     };
     };


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


     mw.calculators.objectClasses.AbstractCalculator.prototype.render = function() {
     mw.calculators.objectClasses.DrugDosageCalculation.prototype.getVariablePrefix = function() {
         if( typeof this.onRender === 'function' ) {
         return this.drug.id + '-';
             this.onRender();
    }
 
    mw.calculators.objectClasses.DrugDosageCalculation.prototype.initialize = function() {
        mw.calculators.objectClasses.AbstractCalculation.prototype.initialize.call( this );
 
        var drug = mw.calculators.getDrug( this.drug );
 
        if( !drug ) {
             throw new Error( 'DrugDosage references drug "' + this.drug + '" which is not defined' );
         }
         }


         this.doRender();
         this.drug = drug;
 
        var variableIds = this.getVariableIds();
 
        // Create variables for indication, population?, preparation select boxes? Here or m.c.addDosages() or elsewhere?
        // Will have to add them to getCalculationData too.
        var drugVariables = {};
 
        var indications = this.drug.getIndications();
        var indicationOptions = {};
 
        for( var iIndication in indications ) {
            var indication = indications[ iIndication ];
 
            indicationOptions[ indication.id ] = String( indication );
        }
 
        drugVariables[ variableIds.indication ] = {
            name: 'Indication',
            type: 'string',
            defaultValue: indications.length ? indications[ 0 ].id : null,
            options: indicationOptions
        };
 
        var preparations = this.drug.getPreparations();
        var preparationOptions = {};
 
        for( var iPreparation in preparations ) {
            var preparation = preparations[ iPreparation ];


        if( typeof this.onRendered === 'function' ) {
            preparationOptions[ preparation.id ] = String( preparation );
            this.onRendered();
         }
         }
    };


        drugVariables[ variableIds.preparation ] = {
            name: 'Preparation',
            type: 'string',
            defaultValue: preparations.length ? preparations[ 0 ].id : null,
            options: preparationOptions
        };


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




Line 1,289: Line 1,091:


     /**
     /**
     * Class SimpleCalculator
     * Class DrugDosageCalculator
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.SimpleCalculator}
     * @returns {mw.calculators.objectClasses.DrugDosageCalculator}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.SimpleCalculator = function( propertyValues ) {
     mw.calculators.objectClasses.DrugDosageCalculator = 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 );
     mw.calculators.objectClasses.DrugDosageCalculator.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculator.prototype );


 
     mw.calculators.objectClasses.DrugDosageCalculator.prototype.doRender = function() {
     mw.calculators.objectClasses.SimpleCalculator.prototype.getProperties = function() {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties();
 
        return this.mergeProperties( inheritedProperties, {
            required: [],
            optional: [
                'css',
                'table'
            ]
        } );
    };
 
    mw.calculators.objectClasses.SimpleCalculator.prototype.doRender = function() {
         var $calculatorContainer = $( '.' + this.getContainerClass() );
         var $calculatorContainer = $( '.' + this.getContainerClass() );


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


         $calculatorContainer.empty();
         $calculatorContainer.empty();


         $calculatorContainer.append( $( '<h4>', {
         var $calculationsContainer = $( '<table>', {
             text: this.name
             class: 'wikitable'
         } ) );
         } ).append( '<tbody>' );


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


         $calculatorContainer.append( $calculationsContainer );
         $calculationsContainer
            .append( $( '<tr>' )
                .append(
                    $( '<th>' ).text( 'Drug' ),
                    $( '<th>' ).text( 'Indication' ),
                    $( '<th>' ).text( 'Dose' )
                )
            );


         for( var iCalculationId in this.calculations ) {
         for( var iCalculationId in this.calculations ) {
Line 1,346: Line 1,130:
             var calculationContainerClass = calculation.getContainerClass();
             var calculationContainerClass = calculation.getContainerClass();


             var $calculationContainer = $( '.' + calculationContainerClass );
             var $calculationContainer = $( '<tr>', {
                class: calculationContainerClass
            } );


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


             calculation.render();
             calculation.render();
Line 1,367: Line 1,140:
     };
     };


     mw.calculators.initialize();
     mw.calculators.objectClasses.DrugDosageCalculator.prototype.getProperties = function() {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties();
 
        return this.mergeProperties( inheritedProperties, {
            required: [],
            optional: []
        } );
    };


}() );
}() );

Revision as of 10:49, 11 August 2021

/**
 * @author Chris Rishel
 */
( function() {
    var DEFAULT_DRUG_COLOR = 'default';
    var DEFAULT_DRUG_POPULATION = 'general';

    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', '%' );

                return units;
            }
        }
    } );

    mw.calculators.addUnits( {
        pct: {
            baseName: 'concentration',
            definition: '10 mg/mL'
        },
        vial: {
            basename: 'VOLUME'
        }
    } );



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

        if( !this.primaryColor && !this.parentColor ) {
            throw new Error( 'Drug color "' + this.id + '" must define either a primary color or a parent color.' );
        }
    };

    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 &&
                !math.largerEq( dataValues[ variableId ], this.variables[ variableId ].min ) ) {
                return -1;
            }

            if( this.variables[ variableId ].max &&
                !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;
    }





    /**
     * 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 ) {
        var properties = {
            required: [
                'id',
                'name'
            ],
            optional: [
                'abbreviation'
            ]
        };

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

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

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





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

        var calculationId = 'drugDosage-' + drugId;
        var calculation = mw.calculators.getCalculation( calculationId );

        if( !calculation ) {
            var calculationData = {};

            calculationData[ calculationId ] = {
                calculate: mw.calculators.objectClasses.DrugDosageCalculation.prototype.calculate,
                drug: drugId,
                type: 'drug'
            };

            mw.calculators.addCalculations( calculationData, 'DrugDosageCalculation' );

            calculation = mw.calculators.getCalculation( calculationId );
        }

        calculation.setDependencies();
    };

    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 ) {
        var properties = {
            required: [
                'id',
                'name'
            ],
            optional: [
                'color'
            ]
        };

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

        if( !this.color ) {
            this.color = DEFAULT_DRUG_COLOR;
        }

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

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

        this.color = color;

        this.dosages = [];
        this.preparations = [];
    };

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

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

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

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

    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.getPreparations = function() {
        return this.preparations.filter( mw.calculators.uniqueValues );
    };





    /**
     * DrugPreparation
     */
    mw.calculators.addDrugPreparations = function( drugId, drugPreparationData ) {
        if( !mw.calculators.getDrug( drugId ) ) {
            throw new Error( 'DrugPreparation references drug "' + drugId + '" which is not defined' );
        }

        for( var drugPreparationId in drugPreparationData ) {
            drugPreparationData[ drugPreparationId ].drug = drugId;
        }

        var drugPreparations = mw.calculators.createCalculatorObjects( 'DrugPreparation', drugPreparationData );

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



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

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

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

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





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

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

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

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

        this.population = drugPopulation;

        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 ) {
        // Each dosage can have one or more associated doses. Ensure this value is an array.
        if( !Array.isArray( drugDoseData ) ) {
            drugDoseData = [ drugDoseData ];
        }

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

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





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

        var mathProperties = this.getMathProperties();

        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 ] )
            } else {
                this[ mathProperty ] = null;
            }
        }

        if( this.weightCalculation ) {
            var weightCalculation = mw.calculators.getCalculation( this.weightCalculation );

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

            this.weightCalculation = weightCalculation;
        }
    };

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

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

        var mathProperties = this.getMathProperties();

        // Look at dose properties to identify any variable dependence (e.g. weight-dependence)
        for( var iMathProperty in mathProperties ) {
            var mathProperty = mathProperties[ iMathProperty ];

            var dosePropertyValue = this[ mathProperty ];

            // For now, this only supports weight dependence, unclear if it will need to be more generalizable in the future
            if( mw.calculators.isValueDependent( dosePropertyValue, 'weight' ) &&
                calculationData.variables.optional.indexOf( 'weight' ) === -1 ) {
                calculationData.variables.optional.push( 'weight' );
            }
        }

        if( this.weightCalculation ) {
            calculationData.calculations.optional.push( this.weightCalculation.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: [
                'absoluteMin',
                'absoluteMax',
                'dose',
                'min',
                'max',
                'name',
                'route',
                'weightCalculation'
            ]
        };
    };




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

        this.initialize();
    };

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

    mw.calculators.objectClasses.DrugDosageCalculation.prototype.calculate = function( data ) {
        var value = {
            population: null,
            dose: []
        };

        // Determine which dosage to use
        var populationScores = [];

        for( var iDosage in data.drug.dosages ) {
            var drugDosage = data.drug.dosages[ iDosage ];

            // If the indication does not match, set the score to -1
            var populationScore = ( drugDosage.indication.id === data.indication.id ) ?
                drugDosage.population.getCalculationDataScore( data ) : -1;

            populationScores.push( populationScore );
        }

        var maxPopulationScore = Math.max.apply( null, populationScores );

        if( maxPopulationScore < 0 ) {
            return value;
        }

        // If there is more than one dosage with the same score, take the first.
        // This allows the data editor to decide which is most important.
        var dosageId = populationScores.indexOf( maxPopulationScore );

        var dosage = data.drug.dosages[ dosageId ];

        value.population = dosage.population;

        // A dosage may contain multiple doses (e.g. induction and maintenance)
        for( var iDose in dosage.dose ) {
            var dose = dosage.dose[ iDose ];
            var mathProperties = dose.getMathProperties();

            // Initialize value properties for dose
            value.dose[ iDose ] = {
                massPerWeight: {},
                mass: {},
                name: dose.name,
                volume: {},
                weightCalculation: dose.weightCalculation ? dose.weightCalculation : null
            };

            var weightValue = dose.weightCalculation ? dose.weightCalculation.value : data.weight;

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

                var doseValue = dose[ mathProperty ];

                if( doseValue ) {
                    if( mw.calculators.isValueDependent( doseValue, 'weight' ) ) {
                        value.dose[ iDose ].massPerWeight[ mathProperty ] = doseValue;

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

                    if( data.preparation && value.dose[ iDose ].mass[ mathProperty ] ) {
                        // Same hack as above to get units to simplify correctly
                        value.dose[ iDose ].volume[ mathProperty ] = math.unit( math.multiply( value.dose[ iDose ].mass[ mathProperty ], math.divide( 1, data.preparation.concentration ) ).format() );
                    }
                }
            }
        }

        return value;
    };

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

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

        $calculationContainer.empty();

        var labelHtml = this.getLabelHtml();
        var labelAttributes = {};
        var labelCss = {
            'background-color': this.drug.color.getPrimaryColor()
        };

        var $infoButton = null;

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

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

        var indicationHtml = '';

        var indications = this.drug.getIndications();

        if( indications.length > 1 ) {
            indicationHtml += mw.calculators.getVariable( this.getVariableIds().indication  ).createInput( true );
        } else {
            indicationHtml += String( indications[ 0 ] );
        }

        var dosageHtml = '';
console.log( this );
        if( this.value.population && this.value.population.id !== DEFAULT_DRUG_POPULATION ) {
            dosageHtml += String( this.value.population ) + '<br />';
        }

        for( var iDose in this.value.dose ) {
            var doseValue = this.value.dose[ iDose ];

            if( doseValue.name ) {
                dosageHtml += doseValue.name + '<br />';
            }

            if( !$.isEmptyObject( doseValue.massPerWeight ) ) {
                if( doseValue.massPerWeight.hasOwnProperty( 'dose' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.dose );
                } else if( doseValue.massPerWeight.hasOwnProperty( 'min' ) &&
                    doseValue.massPerWeight.hasOwnProperty( 'max' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.min );
                    dosageHtml += '-';
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.max );
                }

                if( doseValue.weightCalculation ) {
                    dosageHtml += ' (' + doseValue.weightCalculation.getLabelString() + ')';
                }

                dosageHtml += '<br />';
            }

            if( !$.isEmptyObject( doseValue.mass ) ) {
                if( doseValue.mass.hasOwnProperty( 'dose' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.mass.dose );
                } else if( doseValue.mass.hasOwnProperty( 'min' ) &&
                    doseValue.mass.hasOwnProperty( 'max' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.mass.min );
                    dosageHtml += '-';
                    dosageHtml += mw.calculators.getValueString( doseValue.mass.max );
                }

                dosageHtml += '<br />';
            }

            if( !$.isEmptyObject( doseValue.volume ) ) {
                if( doseValue.volume.hasOwnProperty( 'dose' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.volume.dose );
                } else if( doseValue.volume.hasOwnProperty( 'min' ) &&
                    doseValue.volume.hasOwnProperty( 'max' ) ) {
                    dosageHtml += mw.calculators.getValueString( doseValue.volume.min );
                    dosageHtml += '-';
                    dosageHtml += mw.calculators.getValueString( doseValue.volume.max );
                }

                dosageHtml += '<br />';
            }

            dosageHtml += '<br />';
        }


        $calculationContainer
            .append(
                $( '<th>', labelAttributes ).html( labelHtml ).css( labelCss ),
                $( '<td>' ).html( indicationHtml ),
                $( '<td>' ).html( dosageHtml )
            );


        return;



        var calculation = this;

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




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

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

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

                    var api = new mw.Api();

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

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

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

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

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

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

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


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

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

        // Add variables created by this calculation
        var variableIds = this.getVariableIds();

        for( var variableType in variableIds ) {
            inputData.variables.optional.push( variableIds[ variableType ] );
        }

        var dataTypes = inputData.getDataTypes();

        // Data is only actually required if it is required by every dosage for the drug.
        // Data marked as required by an individual dosage that does not appear in every
        // dosage will be converted to optional.
        var requiredInputData = new mw.calculators.objectClasses.CalculationData();

        // Need a way to tell the first iteration of the loop to initialize the required variables to a value that
        // is distinct from the empty array (populated across loop using array intersect, so could become [] and shouldn't
        // reinitialize).
        var initializeRequiredData = true;

        // Iterate through each dosage to determine variable dependency
        for( var iDosage in this.drug.dosages ) {
            var dosageInputData = this.drug.dosages[ iDosage ].getCalculationData();

            inputData = inputData.merge( dosageInputData );

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

                if( initializeRequiredData ) {
                    requiredInputData[ dataType ].required = inputData[ dataType ].required;
                } else {
                    // Data is only truly required if it is required by all dosage calculations, so use array intersection
                    requiredInputData[ dataType ].required = requiredInputData[ dataType ].required.filter( function( index ) {
                        return dosageInputData[ dataType ].required.indexOf( index ) !== -1;
                    } );
                }
            }

            initializeRequiredData = false;
        }

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

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

            inputData[ dataType ].required = requiredInputData[ dataType ].required;
        }

        return inputData;
    };

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

        data.drug = this.drug;

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

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

        data.preparation = data[ this.getVariablePrefix() + 'preparation' ] ?
            this.drug.preparations[ mw.calculators.getVariable( this.getVariableIds().preparation ).value ] :
            null;

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

        return data;
    };


    mw.calculators.objectClasses.DrugDosageCalculation.prototype.getLabelHtml = function() {
        var labelHtml = this.drug.name;

        var $label = $( '<a>', {
            href: mw.util.getUrl( this.drug.name ),
            text: labelHtml
        } );

        var highlightColor = this.drug.color.getHighlightColor();

        if( highlightColor ) {
            $label.css( 'background-color', highlightColor );
        }

        labelHtml = $label[ 0 ].outerHTML;

        return labelHtml;
    };

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

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

    mw.calculators.objectClasses.DrugDosageCalculation.prototype.getVariableIds = function() {
        return {
            indication: this.getVariablePrefix() + 'indication',
            preparation: this.getVariablePrefix() + 'preparation'
        };
    };

    mw.calculators.objectClasses.DrugDosageCalculation.prototype.getVariablePrefix = function() {
        return this.drug.id + '-';
    }

    mw.calculators.objectClasses.DrugDosageCalculation.prototype.initialize = function() {
        mw.calculators.objectClasses.AbstractCalculation.prototype.initialize.call( this );

        var drug = mw.calculators.getDrug( this.drug );

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

        this.drug = drug;

        var variableIds = this.getVariableIds();

        // Create variables for indication, population?, preparation select boxes? Here or m.c.addDosages() or elsewhere?
        // Will have to add them to getCalculationData too.
        var drugVariables = {};

        var indications = this.drug.getIndications();
        var indicationOptions = {};

        for( var iIndication in indications ) {
            var indication = indications[ iIndication ];

            indicationOptions[ indication.id ] = String( indication );
        }

        drugVariables[ variableIds.indication ] = {
            name: 'Indication',
            type: 'string',
            defaultValue: indications.length ? indications[ 0 ].id : null,
            options: indicationOptions
        };

        var preparations = this.drug.getPreparations();
        var preparationOptions = {};

        for( var iPreparation in preparations ) {
            var preparation = preparations[ iPreparation ];

            preparationOptions[ preparation.id ] = String( preparation );
        }

        drugVariables[ variableIds.preparation ] = {
            name: 'Preparation',
            type: 'string',
            defaultValue: preparations.length ? preparations[ 0 ].id : null,
            options: preparationOptions
        };

        mw.calculators.addVariables( drugVariables );
    };





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

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

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

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

        $calculatorContainer.empty();

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

        $calculatorContainer.append( $calculationsContainer );

        $calculationsContainer
            .append( $( '<tr>' )
                .append(
                    $( '<th>' ).text( 'Drug' ),
                    $( '<th>' ).text( 'Indication' ),
                    $( '<th>' ).text( 'Dose' )
                )
            );

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

            var $calculationContainer = $( '<tr>', {
                class: calculationContainerClass
            } );

            $calculationsContainer.append( $calculationContainer );

            calculation.render();
        }
    };

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

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

}() );