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

From WikiAnesthesia
Tag: Reverted
Tag: Manual revert
 
Line 3: Line 3:
  */
  */
( function() {
( function() {
     var COOKIE_EXPIRATION = 12 * 60 * 60;
     mw.calculators.setOptionValue( 'defaultDrugColor', 'default' );
    mw.calculators.setOptionValue( 'defaultDrugPopulation', 'general' );
    mw.calculators.setOptionValue( 'defaultDrugRoute', 'iv' );


     var TYPE_NUMBER = 'number';
     mw.calculators.isValueDependent = function( value, variableId ) {
    var TYPE_STRING = 'string';
         // This may need generalized to support other variables in the future
 
         if( variableId === 'weight' ) {
    var VALID_TYPES = [
             return value && value.formatUnits().match( /\/[\s(]*?kg/ );
        TYPE_NUMBER,
        } else {
         TYPE_STRING
            throw new Error( 'Dependence "' + variableId + '" not supported by isValueDependent' );
    ];
 
    var DEFAULT_CALCULATION_CLASS = 'SimpleCalculation';
 
    // Polyfill to fetch unit's base. This may become unnecessary in a future version of math.js
    math.Unit.prototype.getBase = function() {
         for( var iBase in math.Unit.BASE_UNITS ) {
             if( this.equalBase( math.Unit.BASE_UNITS[ iBase ] ) ) {
                return iBase;
            }
         }
         }
        return null;
     };
     };


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


    mw.calculators = {
                return units;
        calculations: {},
        objectClasses: {},
        options: {},
        units: {},
        unitsBases: {},
        variables: {},
        addCalculations: function( calculationData, className ) {
            className = className ? className : DEFAULT_CALCULATION_CLASS;
 
            var calculations = mw.calculators.createCalculatorObjects( className, calculationData );
 
            for( var calculationId in calculations ) {
                var calculation = calculations[ calculationId ];
 
                mw.calculators.calculations[ calculationId ] = calculation;
 
                mw.calculators.calculations[ calculationId ].setDependencies();
 
                mw.calculators.calculations[ calculationId ].update();
             }
             }
         },
         },
         addUnitsBases: function( unitsBaseData ) {
         mass: {
            var unitsBases = mw.calculators.createCalculatorObjects( 'UnitsBase', unitsBaseData );
            toString: function( units ) {
                units = units.replace( 'ug', 'mcg' );


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


            for( var unitsId in units ) {
    mw.calculators.addUnits( {
                if( mw.calculators.units.hasOwnProperty( unitsId ) ) {
        Eq: {
                    continue;
            baseName: 'mass_eq',
                }
            prefixes: 'short'
 
                var unitData = {
                    aliases: units[ unitsId ].aliases,
                    baseName: units[ unitsId ].baseName ? units[ unitsId ].baseName.toUpperCase() : units[ unitsId ].baseName,
                    definition: units[ unitsId ].definition,
                    prefixes: units[ unitsId ].prefixes,
                    offset: units[ unitsId ].offset
                };
 
                try {
                    math.createUnit( unitsId, unitData );
                } catch( e ) {
                    console.warn( e.message );
                }
 
                mw.calculators.units[ unitsId ] = units[ unitsId ];
            }
         },
         },
         addVariables: function( variableData ) {
         mcg: {
             var variables = mw.calculators.createCalculatorObjects( 'Variable', variableData );
             baseName: 'mass',
 
             definition: '1 ug'
             for( var variableId in variables ) {
                mw.calculators.variables[ variableId ] = variables[ variableId ];
 
                var cookieValue = mw.calculators.getCookieValue( variableId );
 
                if( cookieValue ) {
                    // Try to set the variable value from the cookie value
                    if( !mw.calculators.variables[ variableId ].setValue( cookieValue ) ) {
                        // Unset the cookie value since for whatever reason it's no longer valid.
                        mw.calculators.setCookieValue( variableId, null );
                    }
                }
            }
         },
         },
         createCalculatorObjects: function( className, objectData ) {
         patch: {
             if( !mw.calculators.objectClasses.hasOwnProperty( className ) ) {
             baseName: 'volume_patch'
                throw new Error( 'Invalid class name "' + className + '"' );
            }
 
            var objects = {};
 
            for( var objectId in objectData ) {
                var propertyValues = objectData[ objectId ];
 
                // Id can either be specified using the 'id' property, or as the property name in objectData
                if( propertyValues.hasOwnProperty( 'id' ) ) {
                    objectId = propertyValues.id;
                }
                else {
                    propertyValues.id = objectId;
                }
 
                objects[ objectId ] = new mw.calculators.objectClasses[ className ]( propertyValues );
            }
 
            return objects;
         },
         },
         createInputGroup: function( variableIds, global ) {
         pct: {
             var $form = $( '<form>', {
             baseName: 'concentration',
                novalidate: true
            definition: '10 mg/mL',
             } );
             formatValue: function( value ) {
 
                var pctMatch = value.match( /([\d.]+)\s*?%/ );
            var $formRow = $( '<div>', {
                class: 'form-row calculator-inputGroup'
            } );


            var inputOptions = {
                if( pctMatch ) {
                global: !!global
                    var pctValue = pctMatch[ 1 ];
            };


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


                 $formRow.append( mw.calculators.variables[ variableId ].createInput( inputOptions ) );
                 return value;
             }
             }
            return $form.append( $formRow );
         },
         },
         getCookieKey: function( variableId ) {
         pill: {
             return 'calculators-var-' + variableId;
             baseName: 'volume_pill'
         },
         },
         getCookieValue: function( varId ) {
         spray: {
             var cookieValue = mw.cookie.get( mw.calculators.getCookieKey( varId ) );
             baseName: 'volume_spray'
 
            if( !cookieValue ) {
                return null;
            }
 
            return cookieValue;
         },
         },
         getCalculation: function( calculationId ) {
         units: {
             if( mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
             baseName: 'mass_units',
                return mw.calculators.calculations[ calculationId ];
            aliases: [
            } else {
                 'unit'
                 return null;
             ]
             }
         },
         },
         getOptionValue: function( optionId ) {
         vial: {
             return mw.calculators.options.hasOwnProperty( optionId ) ?
             baseName: 'volume_vial'
                mw.calculators.options[ optionId ] :
         }
                undefined;
    } );
        },
        getUnitsByBase: function( value ) {
            if( typeof value !== 'object' || !value.hasOwnProperty( 'units' ) ) {
                return null;
            }
 
            var unitsByBase = {};
 
            for( var iUnits in value.units ) {
                var units = value.units[ iUnits ];
 
                // Some units are of a given dimension, but have no conversion definition
                // (e.g. 'units' for mass, 'vial' for volume, etc.). These units are added
                // by appending '_abstract' to the baseName of the unit definition. However,
                // the calculator should treat them as the same type of unit
                var baseId = units.unit.base.key.toLowerCase().replace( /_\w+/, '' );
 
                unitsByBase[ baseId ] = units.prefix.name + units.unit.name;
            }
 
            return unitsByBase;
        },
         getUnitsString: function( value ) {
            if( typeof value !== 'object' ) {
                return null;
            }
 
            var unitsString = value.formatUnits();
 
            var reDenominator = /\/\s?\((.*)\)/;
            var denominatorMatches = unitsString.match( reDenominator );
 
            if( denominatorMatches ) {
                var denominatorUnits = denominatorMatches[ 1 ];
 
                unitsString = unitsString.replace( reDenominator, '/' + denominatorUnits.replace( ' ', '/' ) );
            }
 
            unitsString = unitsString
                .replace( /\s/g, '' )
                .replace( /(\^(\d+))/g, '<sup>$2</sup>' );
 
            var unitsBase = value.getBase();
 
            if( unitsBase ) {
                unitsBase = unitsBase.toLowerCase();
 
                if( mw.calculators.unitsBases.hasOwnProperty( unitsBase ) &&
                    typeof mw.calculators.unitsBases[ unitsBase ].toString === 'function' ) {
                    unitsString = mw.calculators.unitsBases[ unitsBase ].toString( unitsString );
                }
            } else {
                // TODO nasty hack to fix weight units in compound units which have no base
                unitsString = unitsString.replace( 'kgwt', 'kg' );
                unitsString = unitsString.replace( 'ug', 'mcg' );
            }


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


            if( typeof value !== 'number' ) {
                return null;
            }
            // Convert the number to a string, reverse, and count the number of characters up to the period.
            var decimals = value.toString().split('').reverse().join('').indexOf( '.' );
            // If no decimal is present, will be set to -1 by indexOf. If so, set to 0.
            decimals = decimals > 0 ? decimals : 0;
            return decimals;
        },
        getValueNumber: function( value, decimals ) {
            if( !mw.calculators.isValueMathObject( value ) ) {
                return null;
            }
            // Remove floating point errors
            var number = math.round( value.toNumber(), 10 );
            var absNumber = math.abs( number );
            if( absNumber >= 10 || absNumber === 0 ) {
                if( absNumber < 100 && absNumber !== math.round( absNumber ) && 2 * absNumber === math.round( 2 * absNumber ) ) {
                    // Special case to allow nearly-round decimals (e.g. 12.5)
                    decimals = 1;
                } else {
                    decimals = 0;
                }
            } else {
                decimals = -math.floor( math.log10( absNumber ) ) + 1;
            }
            return math.round( number, decimals );
        },
        getValueString: function( value, decimals ) {
            if( !mw.calculators.isValueMathObject( value ) ) {
                return null;
            }
            var valueNumber = mw.calculators.getValueNumber( value, decimals );
            var valueUnits = mw.calculators.getUnitsString( value );
            if( math.abs( math.log10( valueNumber ) ) > 3 ) {
                var valueUnitsByBase = mw.calculators.getUnitsByBase( value );
                var oldSIUnit;
                if( valueUnitsByBase.hasOwnProperty( 'mass' ) ) {
                    oldSIUnit = valueUnitsByBase.mass;
                } else if( valueUnitsByBase.hasOwnProperty( 'volume' ) ) {
                    oldSIUnit = valueUnitsByBase.volume;
                }
                if( oldSIUnit ) {
                    // This new value should simplify to the optimal SI prefix.
                    // We need to create a completely new unit from the formatted (i.e. simplified) value
                    var newSIValue = math.unit( math.unit( valueNumber + ' ' + oldSIUnit ).format() );
                    // There is a bug in mathjs where formatUnits() won't simplify the units, only format() will.
                    var newSIUnit = newSIValue.formatUnits();
                    if( newSIUnit !== oldSIUnit ) {
                        value = math.unit( newSIValue.toNumber() + ' ' + value.formatUnits().replace( oldSIUnit, newSIUnit ) );
                        valueNumber = mw.calculators.getValueNumber( value, decimals );
                        valueUnits = mw.calculators.getUnitsString( value );
                    }
                }
            }
            var valueString = String( valueNumber );
            if( valueUnits ) {
                valueString += ' ' + valueUnits;
            }
            var unitsId = value.formatUnits();
            if( mw.calculators.units.hasOwnProperty( unitsId ) &&
                typeof mw.calculators.units[ unitsId ].formatValue === 'function' ) {
                valueString = mw.calculators.units[ unitsId ].formatValue( valueString );
            }
            return valueString;
        },
        getVariable: function( variableId ) {
            if( mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return mw.calculators.variables[ variableId ];
            } else {
                return null;
            }
        },
        hasData: function( dataType, dataId ) {
            if( mw.calculators.hasOwnProperty( dataType ) &&
                mw.calculators[ dataType ].hasOwnProperty( dataId ) ) {
                return true;
            } else {
                return false;
            }
        },
        initialize: function() {
            // Change the menu item from "article" to "calculator"
            $( '#nav-article svg' ).addClass( 'fa-calculator' );
            $( '#nav-article .nav-label' ).html( 'Calculator' );
            // Wrap description in a collapse
            var descriptionCount = 0;
            $( '.calculator-description' ).each( function() {
                var descriptionContainerId = 'calculator-description-info';
                if( descriptionCount ) {
                    descriptionContainerId += '-' + descriptionCount;
                }
                var $descriptionLinkIcon = $( '<i>', {
                    class: 'far fa-question-circle fa-fw'
                } );
                var descriptionLinkString = '';
                descriptionLinkString += $( this ).data( 'title' ) ? $( this ).data( 'title' ) : 'About this calculator';
                var $descriptionLinkLabel = $( '<span>', {
                    html: descriptionLinkString
                } );
                var $descriptionLink = $( '<a>', {
                    'data-toggle': 'collapse',
                    href: '#' + descriptionContainerId,
                    role: 'button',
                    'aria-expanded': 'false',
                    'aria-controls': descriptionContainerId
                } ).append( $descriptionLinkIcon, $descriptionLinkLabel );
                var $descriptionContainer = $( '<div>', {
                    id: descriptionContainerId,
                    class: 'collapse calculator-description-info',
                    html: $( this ).html()
                } );
                $( this ).empty();
                if( !descriptionCount ) {
                    $descriptionLink.addClass( 'dropdown-item' );
                    $descriptionLinkLabel.addClass( 'nav-label' );
                    $('#menuButton .dropdown-menu').prepend( $descriptionLink );
                } else {
                    $descriptionLink.addClass( 'btn btn-outline-primary btn-sm' );
                    $( this ).append( $descriptionLink );
                }
                $( this ).append( $descriptionContainer );
                descriptionCount++;
            } );
            // Set options
            var $optionsElement = $( '#calculator-options' );
            if( $optionsElement.length ) {
                $.each( $optionsElement.data(), function( optionId, value ) {
                    mw.calculators.setOptionValue( optionId, value );
                } );
            }
        },
        isMobile: function() {
            return window.matchMedia( 'only screen and (max-width: 760px)' ).matches;
        },
        isValueMathObject: function( value ) {
            return value && value.hasOwnProperty( 'value' );
        },
        prepareReferences: function( references ) {
            for( var iReference in references ) {
                var reference = references[ iReference ];
                // http(s)
                reference = reference.replace(
                    /(https?:\/\/[^\s]*)/gmi,
                    '<a href="$1" target="_blank">$1</a>'
                );
                // doi
                reference = reference.replace(
                    /doi: ([\w\d\.\/-]+)((\.\s)|$)/gmi,
                    'doi: <a href="https://doi.org/$1" target="_blank">$1</a>$2'
                );
                // PMCID
                reference = reference.replace(
                    /PMCID: PMC(\d+)/gmi,
                    'PMCID: <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC$1/" target="_blank">PMC$1</a>'
                );
                // PMID
                reference = reference.replace(
                    /PMID: (\d+)/gmi,
                    'PMID: <a href="https://pubmed.ncbi.nlm.nih.gov/$1" target="_blank">$1</a>'
                );
                references[ iReference ] = reference;
            }
            return references;
        },
        setCookieValue: function( variableId, value ) {
            mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
                expires: COOKIE_EXPIRATION
            } );
        },
        setOptionValue: function( optionId, value ) {
            mw.calculators.options[ optionId ] = value;
            return true;
        },
        setValue: function( variableId, value ) {
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return false;
            }
            if( !mw.calculators.variables[ variableId ].setValue( value ) ) {
                return false;
            }
            mw.calculators.setCookieValue( variableId, value );
            return true;
        },
        uniqueValues: function( value, index, self ) {
            return self.indexOf( value ) === index;
        }
    };


     /**
     /**
     * Class CalculatorObject
     * DrugColor
    *
    * @param {Object} properties
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.CalculatorObject}
    * @constructor
     */
     */
     mw.calculators.objectClasses.CalculatorObject = function( properties, propertyValues ) {
     mw.calculators.drugColors = {};
        propertyValues = propertyValues ? propertyValues : {};
 
        if( properties ) {
            if( properties.hasOwnProperty( 'required' ) ) {
                for( var iRequiredProperty in properties.required ) {
                    var requiredProperty = properties.required[ iRequiredProperty ];
 
                    if( !propertyValues || !propertyValues.hasOwnProperty( requiredProperty ) ) {
                        console.error( 'Missing required property "' + requiredProperty + '"' );
                        console.log( propertyValues );
 
                        return null;
                    }
 
                    this[ requiredProperty ] = propertyValues[ requiredProperty ];
 
                    delete propertyValues[ requiredProperty ];
                }
            }
 
            if( properties.hasOwnProperty( 'optional' ) ) {
                for( var iOptionalProperty in properties.optional ) {
                    var optionalProperty = properties.optional[ iOptionalProperty ];
 
                    if( propertyValues && propertyValues.hasOwnProperty( optionalProperty ) ) {
                        this[ optionalProperty ] = propertyValues[ optionalProperty ];
 
                        delete propertyValues[ optionalProperty ];
                    } else if( typeof this[ optionalProperty ] === 'undefined' ) {
                        this[ optionalProperty ] = null;
                    }
                }
            }


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


            if( invalidProperties.length ) {
        for( var drugColorId in drugColors ) {
                console.warn( 'Unsupported properties defined for ' + typeof this + ' with id "' + this.id + '": ' + invalidProperties.join( ', ' ) );
            mw.calculators.drugColors[ drugColorId ] = drugColors[ drugColorId ];
            }
         }
         }
     };
     };


     mw.calculators.objectClasses.CalculatorObject.prototype.getProperties = function() {
     mw.calculators.getDrugColor = function( drugColorId ) {
         return {
         if( mw.calculators.drugColors.hasOwnProperty( drugColorId ) ) {
            required: [],
             return mw.calculators.drugColors[ drugColorId ];
            optional: []
         } else {
        };
            return null;
    };
         }
 
    mw.calculators.objectClasses.CalculatorObject.prototype.mergeProperties = function( inheritedProperties, properties ) {
        var uniqueValues = function( value, index, self ) {
             return self.indexOf( value ) === index;
         };
 
        properties.required = inheritedProperties.required.concat( properties.required ).filter( uniqueValues );
         properties.optional = inheritedProperties.optional.concat( properties.optional ).filter( uniqueValues );
 
        return properties;
     };
     };


     /**
     /**
     * Class UnitsBase
     * Class DrugColor
     * @param {Object} propertyValues
     * @param {Object} propertyValues
     * @returns {mw.calculators.objectClasses.UnitsBase}
     * @returns {mw.calculators.objectClasses.DrugColor}
     * @constructor
     * @constructor
     */
     */
     mw.calculators.objectClasses.UnitsBase = function( propertyValues ) {
     mw.calculators.objectClasses.DrugColor = function( propertyValues ) {
         var properties = {
         var properties = {
             required: [
             required: [
Line 553: Line 116:
             ],
             ],
             optional: [
             optional: [
                 'toString'
                 'parentColor',
                'primaryColor',
                'highlightColor',
                'striped'
             ]
             ]
         };
         };


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


         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
         this.parentColor = this.parentColor || this.id === mw.calculators.getOptionValue( 'defaultDrugColor' ) ? this.parentColor : mw.calculators.getOptionValue( 'defaultDrugColor' );
     };
     };


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


 
     mw.calculators.objectClasses.DrugColor.prototype.getParentDrugColor = function() {
 
         if( !this.parentColor ) {
 
             return null;
     /**
    * Class Variable
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.Variable}
    * @constructor
    */
    mw.calculators.objectClasses.Variable = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
 
         if( VALID_TYPES.indexOf( this.type ) === -1 ) {
             throw new Error( 'Invalid type "' + this.type + '" for variable "' + this.id + '"' );
         }
         }


         // Accept options as either an array of strings, or an object with ids as keys and display text as values
         var parentDrugColor = mw.calculators.getDrugColor( this.parentColor );
        if( Array.isArray( this.options ) ) {
            var options = {};
 
            for( var iOption in this.options ) {
                var option = this.options[ iOption ];
 
                options[ option ] = option;
            }


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


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


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


         if( this.minValue ) {
    mw.calculators.objectClasses.DrugColor.prototype.getPrimaryColor = function() {
             this.minValue = this.prepareValue( this.minValue );
         if( this.primaryColor ) {
             return this.primaryColor;
        } else if( this.parentColor ) {
            return this.getParentDrugColor().getPrimaryColor();
         }
         }
        if( this.maxValue ) {
            this.maxValue = this.prepareValue( this.maxValue );
        }
        this.message = null;
        this.valid = true;
        this.isValueSet = false;
        this.value = null;
     };
     };


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


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


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


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


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


            while( $( '#' + inputId + '-' + inputIdCount ).length ) {
    /**
                inputIdCount++;
    * DrugPopulation
            }
    */
 
            inputId += '-' + inputIdCount;
        }
 
        var inputContainerTag = inputOptions.inline ? '<span>' : '<div>';
 
        var inputContainerAttributes = {
            class: 'form-group mb-0 calculator-container-input'
        };


        inputContainerAttributes.class += inputOptions.class ? ' ' + inputOptions.class : '';
    mw.calculators.drugPopulations = {};
        inputContainerAttributes.class += ' calculator-container-input-' + variableId;


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


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


        var labelCss = {};
    mw.calculators.getDrugPopulation = function( drugPopulationId ) {
 
         if( mw.calculators.drugPopulations.hasOwnProperty( drugPopulationId ) ) {
         if( inputOptions.inline ) {
             return mw.calculators.drugPopulations[ drugPopulationId ];
             inputContainerTag = '<span>';
        } else {
 
             return null;
            inputContainerCss[ 'align-items' ] = 'center';
            inputContainerCss[ 'display' ] = 'flex';
            //inputContainerCss[ 'height' ] = 'calc(1.5em + 0.75rem + 2px)';
 
            labelAttributes.html += ':&nbsp;';
             labelCss[ 'margin-bottom' ] = 0;
         }
         }
    };


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


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


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


         // 'this' will be redefined for event handlers
         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
        var variable = this;
        var value = this.getValue();
 
        if( this.type === TYPE_NUMBER ) {
            // Initialize the primary units variables (needed for handlers, even if doesn't have units)
            var unitsId = null;
            var $unitsContainer = null;
 
            var inputValue = '';
 
            if( mw.calculators.isValueMathObject( value ) ) {
                var number = value.toNumber();


                 if( number ) {
        if( this.variables ) {
                     inputValue = number;
            for( var variableId in this.variables ) {
                 if( !mw.calculators.getVariable( variableId ) ) {
                     throw new Error( 'DrugPopulation variable "' + variableId + '" not defined' );
                 }
                 }
            } else {
                inputValue = value;
            }


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


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


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


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


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


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


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


                // Create the units container
        for( var variableId in this.variables ) {
                $unitsContainer = $( '<div>', {
            if( !dataValues.hasOwnProperty( variableId ) ) {
                    class: 'input-group-append'
                return -1;
                } ).css( 'align-items', 'center' );
            }
 
                if( this.units.length === 1 ) {
                    unitsInputAttributes.type = 'hidden';
                    unitsInputAttributes.value = this.units[ 0 ];
 
                    $unitsContainer
                        .css( 'padding', '0 0.5em' )
                        .append( mw.calculators.getUnitsString( math.unit( '0 ' + this.units[ 0 ] ) ) )
                        .append( $( '<input>', unitsInputAttributes ) );
                } else {
                    // Initialize the units input options
                    unitsInputAttributes.class = 'custom-select custom-select-sm calculator-input-select';
 
                    // Add any additional classes to the input
                    unitsInputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
 
                    unitsInputAttributes.class = unitsInputAttributes.class + ' ' + unitsId;
 
                    var $unitsInput = $( '<select>', unitsInputAttributes )
                        .on( 'change', function() {
                            var numberValue = $( '#' + inputId ).val();
 
                            var newValue = numberValue ? numberValue + ' ' + $( this ).val() : null;
 
                            if( !mw.calculators.setValue( variableId, newValue ) ) {
                                if( variable.message ) {
                                    $( this ).parent().parent().parent().find( '.invalid-feedback' ).html( variable.message );
                                }
 
                                $( this ).parent().parent().addClass( 'is-invalid' );
                            } else {
                                $( this ).parent().parent().removeClass( 'is-invalid' );
                            }
                        } );
 
                    for( var iUnits in this.units ) {
                        var units = this.units[ iUnits ];
 
                        var unitsOptionAttributes = {
                            html: mw.calculators.getUnitsString( math.unit( '0 ' + units ) ),
                            value: units
                        };


                        if( units === unitsValue ) {
            if( this.variables[ variableId ].min &&
                            unitsOptionAttributes.selected = true;
                ( !dataValues[ variableId ] ||
                        }
                    !math.largerEq( dataValues[ variableId ], this.variables[ variableId ].min ) ) ) {
 
                 return -1;
                        $unitsInput.append( $( '<option>', unitsOptionAttributes ) );
                    }
 
                    $unitsContainer.append( $unitsInput );
                 }
             }
             }


             // Create the input and add handlers
             if( this.variables[ variableId ].max &&
            var $input = $( '<input>', inputAttributes )
                ( !dataValues[ variableId ] ||
                .on( 'input', function() {
                     !math.smallerEq( dataValues[ variableId ], this.variables[ variableId ].max ) ) ) {
                    var numberValue = $( this ).val();
                 return -1;
 
                    var newValue = numberValue ? numberValue : null;
 
                    if( newValue && unitsId ) {
                        newValue = newValue + ' ' + $( '#' + unitsId ).val();
                     }
 
                    if( !mw.calculators.setValue( variableId, newValue ) ) {
                        if( variable.message ) {
                            $( this ).parent().parent().find( '.invalid-feedback' ).html( variable.message );
                        }
 
                        $( this ).parent().addClass( 'is-invalid' );
                    } else {
                        $( this ).parent().removeClass( 'is-invalid' );
                    }
                 } );
 
            // Create the input group
            var $inputGroup = $( '<div>', {
                class: 'input-group'
            } ).append( $input );
 
            if( $unitsContainer ) {
                $inputGroup.append( $unitsContainer );
             }
             }
        }


            $inputContainer.append( $inputGroup );
        // If the data matches the population definition, the score corresponds to the number of variables in the
         } else if( this.type === TYPE_STRING ) {
         // population definition. This should roughly correspond to the specificity of the population.
            if( this.hasOptions() ) {
        return Object.keys( this.variables ).length;
                var optionKeys = Object.keys( this.options );
    };


                if( optionKeys.length === 1 ) {
    mw.calculators.objectClasses.DrugPopulation.prototype.toString = function() {
                    $inputContainer.append( this.options[ optionKeys[ 0 ] ] );
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
                } else {
    };
                    var selectAttributes = {
                        id: inputId,
                        class: 'custom-select custom-select-sm calculator-input calculator-input-select'
                    };


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


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


                                $( this ).parent().addClass( 'is-invalid' );
    /**
                            } else {
    * DrugRoute
                                $( this ).parent().removeClass( 'is-invalid' );
    */
                            }
    mw.calculators.drugRoutes = {};


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


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


                        var optionAttributes = {
    mw.calculators.getDrugRoute = function( drugRouteId ) {
                            value: optionId,
        if( mw.calculators.drugRoutes.hasOwnProperty( drugRouteId ) ) {
                            text: displayText
            return mw.calculators.drugRoutes[ drugRouteId ];
                        };
        } else {
 
             return null;
                        if( optionId == value ) {
                            optionAttributes.selected = true;
                        }
 
                        $select.append( $( '<option>', optionAttributes ) );
                    }
 
                    $inputContainer.append( $select );
                }
             }
         }
         }
    };


        if( $inputContainer.length ) {
    /**
            $inputContainer.append( $( '<div>', {
    * Class DrugRoute
                class: 'invalid-feedback'
    * @param {Object} propertyValues
            } ) );
    * @returns {mw.calculators.objectClasses.DrugRoute}
        }
    * @constructor
    */
    mw.calculators.objectClasses.DrugRoute = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


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


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


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


     mw.calculators.objectClasses.Variable.prototype.getValue = function() {
     mw.calculators.objectClasses.DrugRoute.prototype.toString = function() {
         if( !this.valid ) {
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
            return null;
        } else if( this.value !== null ) {
            return this.value;
        } else if( !this.isValueSet && this.defaultValue !== null ) {
            return this.defaultValue;
        } else {
            return null;
        }
     };
     };


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


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


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


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


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


        return true;
    };


     mw.calculators.objectClasses.Variable.prototype.isValueMathObject = function() {
    /**
         return mw.calculators.isValueMathObject( this.value );
    * DrugIndication
    };
    */
     mw.calculators.drugIndications = {};
 
    mw.calculators.addDrugIndications = function( drugIndicationData ) {
         var drugIndications = mw.calculators.createCalculatorObjects( 'DrugIndication', drugIndicationData );


    mw.calculators.objectClasses.Variable.prototype.prepareValue = function( value ) {
         for( var drugIndicationId in drugIndications ) {
         if( value !== null ) {
             mw.calculators.drugIndications[ drugIndicationId ] = drugIndications[ drugIndicationId ];
             if( this.type === TYPE_NUMBER ) {
                if( !mw.calculators.isValueMathObject( value ) ) {
                    value = math.unit( value );
                }
            }
         }
         }
        return value;
     };
     };


     mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
     mw.calculators.getDrugIndication = function( drugIndicationId ) {
         // Set flag to prevent returning defaultValue in getValue()
         if( mw.calculators.drugIndications.hasOwnProperty( drugIndicationId ) ) {
        this.isValueSet = true;
             return mw.calculators.drugIndications[ drugIndicationId ];
 
        } else {
        var validateResult = this.validateValue( value );
             return null;
 
        this.valid = !!validateResult.valid;
        this.message = validateResult.message;
 
        if( !this.valid ) {
             this.value = null;
            this.valueUpdated();
 
             return false;
         }
         }
    };


        this.value = this.prepareValue( value );
    /**
 
    * Class DrugIndication
         this.valueUpdated();
    * @param {Object} propertyValues
 
    * @returns {mw.calculators.objectClasses.DrugIndication}
        return true;
    * @constructor
    */
    mw.calculators.objectClasses.DrugIndication = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
     };
     };


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


     mw.calculators.objectClasses.Variable.prototype.validateValue = function( value ) {
     mw.calculators.objectClasses.DrugIndication.prototype.getProperties = function() {
         // Initialize valid flag to true. Will be set false if an error is found.
         return {
        result = {
             required: [
             message: null,
                'id',
             valid: true
                'name'
             ],
            optional: [
                'abbreviation',
                'default',
                'searchData'
            ]
         };
         };
    };


        // (At least for now) unsetting a variable is always valid
    mw.calculators.objectClasses.DrugIndication.prototype.getSearchString = function() {
         if( value === null ) {
         var searchString = this.name;
            return result;
        }


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


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


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


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


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


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


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


            if( this.minValue && math.smaller( value, this.minValue ) ) {
    /**
                var minValueString = mw.calculators.getValueString( this.minValue );
    * Drug
    */
    mw.calculators.drugs = {};


                if( valueUnits && valueUnits != this.minValue.formatUnits() ) {
    mw.calculators.addDrugs = function( drugData ) {
                    minValueString += ' (' + mw.calculators.getValueString( this.minValue.to( valueUnits ) ) + ')';
        var drugs = mw.calculators.createCalculatorObjects( 'Drug', drugData );
                }


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


                if( valueUnits && valueUnits != this.maxValue.formatUnits() ) {
    mw.calculators.addDrugDosages = function( drugId, drugDosageData ) {
                    maxValueString += ' (' + mw.calculators.getValueString( this.maxValue.to( valueUnits ) ) + ')';
        var drug = mw.calculators.getDrug( drugId );
                }


                result.message = String( this ) + ' must be less than ' + maxValueString;
         if( !drug ) {
                result.valid = false;
             throw new Error( 'DrugDosage references drug "' + drugId + '" which is not defined' );
            }
         } else if( this.hasOptions() ) {
             if( !this.options.hasOwnProperty( value ) ) {
                // Unlikely to be a user error, so don't set message
                result.valid = false;
 
                console.warn( consoleWarnPrefix + 'Value must be one of: ' + Object.keys( this.options ).join( ', ' ) );
            }
         }
         }


         return result;
         drug.addDosages( drugDosageData );
     };
     };


     mw.calculators.objectClasses.Variable.prototype.valueUpdated = function() {
     mw.calculators.getDrug = function( drugId ) {
         for( var iCalculation in this.calculations ) {
         if( mw.calculators.drugs.hasOwnProperty( drugId ) ) {
             var calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );
             return mw.calculators.drugs[ drugId ];
 
        } else {
             if( calculation ) {
             return null;
                calculation.update();
            }
         }
         }
     };
     };
Line 1,104: Line 433:


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


         this.initialize();
         if( !this.color ) {
    };
            this.color = mw.calculators.getOptionValue( 'defaultDrugColor' );
 
    mw.calculators.objectClasses.AbstractCalculation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.addCalculation = function( calculationId ) {
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
            return;
         }
         }


         this.calculations.push( calculationId );
         var color = mw.calculators.getDrugColor( this.color );
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.doRender = function() {
        throw new Error( 'AbstractCalculation child class "' + this.getClassName() + '" must implement doRender()' );
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationData = function() {
        return this.data;
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationDataValues = function() {
        var calculationData = this.getCalculationData();


        var missingRequiredData = this.getMissingRequiredData();
         if( !color ) {
 
             throw new Error( 'Invalid drug color "' + this.color + '" for drug "' + this.id + '"' );
         if( missingRequiredData.length ) {
             this.message = missingRequiredData.join( ', ' ) + ' required';
 
            return false;
         }
         }


         var data = {};
         this.color = color;


         var calculationId, calculation, variableId, variable;
         if( this.preparations ) {
            var preparationData = this.preparations;


        var calculations = calculationData.calculations.required.concat( calculationData.calculations.optional );
            this.preparations = [];


        for( var iRequiredCalculation in calculations ) {
             this.addPreparations( preparationData );
             calculationId = calculations[ iRequiredCalculation ];
        } else {
            calculation = mw.calculators.getCalculation( calculationId );
             this.preparations = [];
 
             // We shouldn't use getValue() since that triggers recalculate() which would cause an infinite loop
            data[ calculationId ] = calculation.value;
         }
         }


         var variables = calculationData.variables.required.concat( calculationData.variables.optional );
         if( this.dosages ) {
            var dosageData = this.dosages;


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


             data[ variableId ] = variable.getValue();
             this.addDosages( dosageData );
        } else {
            this.dosages = [];
         }
         }


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


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


     mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerClasses = function() {
     mw.calculators.objectClasses.Drug.prototype.addDosages = function( dosageData ) {
         return this.getElementClasses();
         var dosages = mw.calculators.createCalculatorObjects( 'DrugDosage', dosageData );
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerId = function() {
        for( var dosageId in dosages ) {
        return this.getElementPrefix() + '-' + this.id;
            dosages[ dosageId ].id = this.dosages.length;
    };


    mw.calculators.objectClasses.AbstractCalculation.prototype.getDescription = function() {
            this.dosages.push( dosages[ dosageId ] );
         return this.description;
         }
     };
     };


     mw.calculators.objectClasses.AbstractCalculation.prototype.getElementPrefix = function( useClassName ) {
     mw.calculators.objectClasses.Drug.prototype.addPreparations = function( preparationData ) {
         var elementPrefix = 'calculator-';
         var preparations = mw.calculators.createCalculatorObjects( 'DrugPreparation', preparationData );


         elementPrefix += useClassName ? this.getClassName() : 'calculation';
         for( var preparationId in preparations ) {
            preparations[ preparationId ].id = this.preparations.length;


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


     mw.calculators.objectClasses.AbstractCalculation.prototype.getElementClasses = function( elementId ) {
     mw.calculators.objectClasses.Drug.prototype.getIndications = function() {
         elementId = elementId ? '-' + elementId : '';
         var indications = [];


         return this.getElementPrefix() + elementId + ' ' +
         for( var iDosage in this.dosages ) {
             this.getElementPrefix( true ) + elementId + ' ' +
             if( this.dosages[ iDosage ].indication ) {
            this.getContainerId() + elementId;
                indications.push( this.dosages[ iDosage ].indication );
    };
            }
        }


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


     mw.calculators.objectClasses.AbstractCalculation.prototype.getInfo = function( infoCount ) {
     mw.calculators.objectClasses.Drug.prototype.getPopulations = function( indicationId ) {
         var infoHtml = '';
         var populations = [];
 
        var description = this.getDescription();
 
        if( description ) {
            infoHtml += $( '<p>', {
                html: description
            } )[ 0 ].outerHTML;
        }
 
        var formula = this.getFormula();


         if( formula ) {
         for( var iDosage in this.dosages ) {
             infoHtml += $( '<div>', {
             if( this.dosages[ iDosage ].population &&
                 class: this.getElementClasses( 'formula' )
                 ( !indicationId || ( this.dosages[ iDosage ].indication && this.dosages[ iDosage ].indication.id === indicationId ) ) ) {
            } )[ 0 ].outerHTML;
                 populations.push( this.dosages[ iDosage ].population );
        }
 
        var references = this.getReferences();
 
        if( references.length ) {
            var $references = $( '<ol>' );
 
            for( var iReference in references ) {
                 $references.append( $( '<li>', {
                    html: references[ iReference ]
                } ) );
             }
             }
            infoHtml += $( '<div>', {
                class: this.getElementClasses( 'references' )
            } ).append( $references )[ 0 ].outerHTML;
        }
        var infoContainerId = this.getContainerId() + '-info';
        if( infoCount ) {
            infoContainerId += '-' + infoCount;
         }
         }


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


     mw.calculators.objectClasses.AbstractCalculation.prototype.getInfoButton = function( infoCount ) {
     mw.calculators.objectClasses.Drug.prototype.getRoutes = function( indicationId ) {
         var infoContainerId = this.getContainerId() + '-info';
         var routes = [];


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


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


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


         var missingRequiredData = [];
         if( excludeDilutionRequired ) {
        var calculation, variable;
             for( var iPreparation in preparations ) {
 
                if( preparations[ iPreparation ].dilutionRequired ) {
        for( var iRequiredCalculation in calculationData.calculations.required ) {
                    delete preparations[ iPreparation ];
            calculation = mw.calculators.getCalculation( calculationData.calculations.required[ iRequiredCalculation ] );
                 }
 
            if( !calculation.hasValue() ) {
                missingRequiredData = missingRequiredData.concat( calculation.getMissingRequiredData() );
             }
        }
 
        for( var iRequiredVariable in calculationData.variables.required ) {
            variable = mw.calculators.getVariable( calculationData.variables.required[ iRequiredVariable ] );
 
            if( !variable.hasValue() ) {
                 missingRequiredData.push( String( variable ) );
             }
             }
         }
         }


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


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


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


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


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


        return searchString.trim();
    };


     mw.calculators.objectClasses.AbstractCalculation.prototype.getTitleHtml = function() {
    /**
         return this.getTitleString();
    * DrugPreparation
    };
    */
     mw.calculators.addDrugPreparations = function( drugId, drugPreparationData ) {
         var drug = mw.calculators.getDrug( drugId );


    mw.calculators.objectClasses.AbstractCalculation.prototype.getTitleString = function() {
        if( !drug ) {
        return this.id;
            throw new Error( 'DrugPreparation references drug "' + drugId + '" which is not defined' );
    };
        }


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


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


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


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


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


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


         this.data = new mw.calculators.objectClasses.CalculationData( this.getCalculationData() );
         this.concentration = this.concentration.replace( 'mcg', 'ug' );


         this.references = this.references ? mw.calculators.prepareReferences( this.references ) : [];
         this.concentration = math.unit( this.concentration );
    };


        this.type = this.type ? this.type : TYPE_NUMBER;
    mw.calculators.objectClasses.DrugPreparation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );


        this.message = null;
    mw.calculators.objectClasses.DrugPreparation.prototype.getVolumeUnits = function() {
         this.value = null;
         // The units of concentration will always be of the form "mass / volume"
 
         // The regular expression matches all text leading up to the volume units
         // Remove any placeholder content explicitly set in the markup (used for SEO).
         return mw.calculators.getUnitsByBase( this.concentration ).volume;
         $( '.' + this.getContainerId() ).empty();
     };
     };


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


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


        if( !formula ) {
            return;
        }


        var api = new mw.Api();


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


        api.parse( formula ).then( function( result ) {
    /**
            $( '.' + containerId ).html( result );
    * Class DrugDosage
        } );
    * @param {Object} propertyValues
    };
    * @returns {mw.calculators.objectClasses.DrugDosage}
    * @constructor
    */
    mw.calculators.objectClasses.DrugDosage = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );


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


        var data = this.getCalculationDataValues();
         if( !drugIndication ) {
 
             throw new Error( 'Invalid indication "' + this.indication + '" for drug dosage' );
         if( data === false ) {
             this.valueUpdated();
 
            return false;
         }
         }


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


            if( this.type === TYPE_NUMBER && !isNaN( value ) ) {
        this.population = this.population ? this.population : mw.calculators.getOptionValue( 'defaultDrugPopulation' );
                if( this.units ) {
                    value = value + ' ' + this.units;
                }


                this.value = math.unit( value );
        var drugPopulation = mw.calculators.getDrugPopulation( this.population );
            } else {
                this.value = value;
            }
      } catch( e ) {
            console.warn( e.message );


            this.message = e.message;
         if( !drugPopulation ) {
            this.value = null;
             throw new Error( 'Invalid population "' + this.population + '" for drug dosage' );
         } finally {
             this.valueUpdated();
         }
         }


         return true;
         this.population = drugPopulation;
    };


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


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


    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
         if( !Array.isArray( this.routes ) ) {
        // Need to run rendering in setTimeout to allow browser events to remain responsive
             this.routes = [ this.routes ];
        var calculation = this;
         }
 
         setTimeout( function() {
            if( typeof calculation.onRender === 'function' ) {
                calculation.onRender();
            }
 
            calculation.doRender();
 
            // Send API queries to parse LaTeX formulas
            calculation.parseFormula();
 
             mw.track( 'mw.calculators.CalculationRendered' );
 
            if( typeof calculation.onRendered === 'function' ) {
                calculation.onRendered();
            }
         }, 0 );
    };


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


         var calculationIds = this.data.calculations.required.concat( this.data.calculations.optional );
         for( var iRoute in this.routes ) {
            var drugRouteId = this.routes[ iRoute ];
            var drugRoute = mw.calculators.getDrugRoute( drugRouteId );


        for( var iCalculationId in calculationIds ) {
             if( !drugRoute ) {
            var calculationId = calculationIds[ iCalculationId ];
                 throw new Error( 'Invalid route "' + drugRouteId + '" for drug dosage' );
 
             if( !mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
                 throw new Error('Calculation "' + calculationId + '" does not exist for calculation "' + this.id + '"');
             }
             }


             mw.calculators.calculations[ calculationId ].addCalculation( this.id );
             drugRoutes[ iRoute ] = drugRoute;
         }
         }


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


         for( var iVariableId in variableIds ) {
         // Add the dose objects to the drug
            var variableId = variableIds[ iVariableId ];
        var drugDoseData = this.dose;
        this.dose = [];


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


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


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


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


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


             if( calculation ) {
             this.dose.push( doses[ doseId ] );
                calculation.update();
            }
         }
         }
     };
     };


    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 ) {
    * Class CalculationData
             inputData = inputData.merge( this.dose[ iDose ].getCalculationData() );
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.CalculationData}
    * @constructor
    */
    mw.calculators.objectClasses.CalculationData = function( propertyValues ) {
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
 
        var dataTypes = this.getDataTypes();
        var dataRequirements = this.getDataRequirements();
 
        // Iterate through the supported data types (e.g. calculation, variable) to initialize the structure
        for( var iDataType in dataTypes ) {
             var dataType = dataTypes[ iDataType ];
 
            if( !this[ dataType ] ) {
                this[ dataType ] = {
                    optional: [],
                    required: []
                };
            } else {
                // Iterate through the requirement levels (i.e. optional, required) to initialize the structure
                for( var iDataRequirement in dataRequirements ) {
                    var dataRequirement = dataRequirements[ iDataRequirement ];
 
                    // FYI can't check to see if the data actually exists here since it may not be defined yet
                    if( !this[ dataType ].hasOwnProperty( dataRequirement ) ) {
                        this[ dataType ][ dataRequirement ] = [];
                    }
                }
            }
         }
         }
    };
    mw.calculators.objectClasses.CalculationData.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
    mw.calculators.objectClasses.CalculationData.prototype.getDataRequirements = function() {
        return [
            'optional',
            'required'
        ];
    };


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


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


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


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


        return routeString;
    };


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


Line 1,608: Line 758:


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


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


    mw.calculators.objectClasses.SimpleCalculation.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculation.prototype );
            // weightCalculation property will contain references to the actual objects, so reinitialize
            this.weightCalculation = [];


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


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


        // Add all required classes
                if( !weightCalculation ) {
        $calculationContainer.addClass( 'row no-gutters border ' + this.getContainerClasses() );
                    throw new Error( 'Drug dose references weight calculation "' + weightCalculationId + '" which is not defined' );
 
                }
        // Add search phrases
        $calculationContainer.attr( 'data-search', this.getSearchString() );
 
        // Get a string version of the calculation's value
        var valueString = this.getValueString();


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


        // Out of 12, uses Bootstrap col- classes in a container
         var mathProperties = this.getMathProperties();
         var titleColumns = '7';
         var isWeightDependent = false;
         var valueColumns = '5';


         // Store this object in a local variable since .each() will reassign this to the DOM object of each
         for( var iMathProperty in mathProperties ) {
        // calculation container.
            var mathProperty = mathProperties[ iMathProperty ];
        var calculation = this;
        var calculationCount = 0;


        // Eventually may implement different rendering, so we should regenerate
            if( this[ mathProperty ] ) {
        // all elements with each iteration of the loop.
                // TODO consider making a UnitsBase.weight.fromString()
        // I.e. might show result in table and inline in 2 different places of article.
                this[ mathProperty ] = this[ mathProperty ].replace( 'kg', 'kgwt' );
        $calculationContainer.each( function() {
                 this[ mathProperty ] = this[ mathProperty ].replace( 'mcg', 'ug' );
            // Initalize the variables for all the elements of the calculation. These need to be in order of placement
            // in the calculation container
            var elementTypes = [
                'title',
                'variables',
                 'value',
                'info'
            ];


            var elements = {};
                this[ mathProperty ] = math.unit( this[ mathProperty ] );


            for( var iElementType in elementTypes ) {
                if( mw.calculators.isValueDependent( this[ mathProperty ], 'weight' ) ) {
                var elementType = elementTypes[ iElementType ];
                     isWeightDependent = true;
 
                elements[ elementType ] = {
                    $container: null,
                    id: calculation.getContainerId() + '-' + elementType
                };
 
                if( calculationCount ) {
                     elements[ elementType ].id += '-' + calculationCount;
                 }
                 }
            } else {
                this[ mathProperty ] = null;
             }
             }
        }


             // Create title element and append to container
        if( isWeightDependent ) {
             elements.title.$container = $( '<div>', {
             // Default is tbw
                id: elements.title.id
             this.weightCalculation.push( mw.calculators.getCalculation( 'tbw' ) );
            } );
        }
    };


            elements.title.$container.append( calculation.getTitleHtml() );
    mw.calculators.objectClasses.DrugDose.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );


            if( calculation.hasInfo() ) {
    mw.calculators.objectClasses.DrugDose.prototype.getAdministration = function() {
                elements.title.$container.append( calculation.getInfoButton( calculationCount ) );
        var administration = '';


                // Id of the info container should already be set by getInfo()
        if( this.frequency ) {
                elements.info.$container = calculation.getInfo();
            administration += administration ? ' ' : '';
            }
            administration += this.frequency;
        }


             // Create the value element
        if( this.duration ) {
             elements.value.$container = $( '<div>' ).append( valueString );
             administration += administration ? ' ' : '';
             administration += 'over ' + this.duration;
        }


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


                // Add the id attribute to the value container
    mw.calculators.objectClasses.DrugDose.prototype.getCalculationData = function() {
                elements.value.$container.attr( 'id', elements.value.id );
        var calculationData = new mw.calculators.objectClasses.CalculationData();


                elements.value.$container.addClass( 'col-' + valueColumns );
        for( var iWeightCalculation in this.weightCalculation ) {
            } else {
            calculationData.calculations.optional.push( this.weightCalculation[ iWeightCalculation ].id );
                // If we need to show variable inputs, make the title span the full width of the container,
        }
                // put the variable inputs on a new row, and show the result on a row below that.
                elements.title.$container.addClass( 'col-12 border-bottom' );
                elements.value.$container.addClass( 'col-12' );
 
                // Create a new row for the variable inputs
                elements.variables.$container = $( '<div>', {
                    class: 'row no-gutters border-bottom ' + calculation.getElementClasses( 'variables' ),
                    id: elements.variables.id
                } )
                    .append( $( '<div>', {
                        class: 'col-12'
                    } )
                        .append( mw.calculators.createInputGroup( missingVariableInputs ) ) );
 
                elements.value.$container = $( '<div>', {
                    class: 'row no-gutters',
                    id: elements.value.id
                } )
                    .append(
                        elements.value.$container
                );
            }


            // Add the title classes after the layout classes
         return calculationData;
            elements.title.$container.addClass( calculation.getElementClasses( 'title' ) );
 
            elements.value.$container.addClass( calculation.getElementClasses( 'value' ) );
 
            // Iterate over elementTypes since it is in order of rendering
            for( var iElementType in elementTypes ) {
                var elementType = elementTypes[ iElementType ];
 
                var $existingContainer = $( '#' + elements[ elementType ].id );
 
                if( $existingContainer.length ) {
                    // If an input within this container has focus (i.e. the user changed a variable input which
                    // triggered this rerender), don't rerender the element as this would destroy the focus on
                    // the input.
                    if( !$.contains( $existingContainer[ 0 ], $( ':focus' )[ 0 ] ) ) {
                        $existingContainer.replaceWith( elements[ elementType ].$container );
                    }
                } else {
                    $( this ).append( elements[ elementType ].$container );
                }
            }
 
            calculationCount++;
         } );
     };
     };


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


     mw.calculators.objectClasses.SimpleCalculation.prototype.getProperties = function() {
     mw.calculators.objectClasses.DrugDose.prototype.getProperties = function() {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();
         return {
 
         return this.mergeProperties( inheritedProperties, {
             required: [
             required: [
                 'name'
                 'id'
             ],
             ],
             optional: [
             optional: [
                 'abbreviation',
                 'absoluteMax',
                 'digits',
                 'absoluteMin',
                 'link',
                 'dose',
                 'units'
                 'duration',
                'frequency',
                'min',
                'max',
                'name',
                'text',
                'weightCalculation'
             ]
             ]
         } );
         };
    };
 
    mw.calculators.objectClasses.SimpleCalculation.prototype.getSearchString = function() {
        return ( this.id + ' ' + this.abbreviation + ' ' + this.name + ' ' + this.searchData ).trim();
    };
 
    mw.calculators.objectClasses.SimpleCalculation.prototype.getTitleHtml = function() {
        var titleHtml = this.getTitleString();
 
        if( this.link ) {
            var href = this.link;
 
            // Detect internal links (this isn't great)
            var matches = href.match( /\[\[(.*?)\]\]/ );
 
            if( matches ) {
                href = mw.util.getUrl( matches[ 1 ] );
            }
 
            titleHtml = $( '<a>', {
                href: href,
                text: titleHtml
            } )[ 0 ].outerHTML;
        }
 
        return titleHtml;
     };
     };
    mw.calculators.objectClasses.SimpleCalculation.prototype.getTitleString = function() {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
    };
    mw.calculators.objectClasses.SimpleCalculation.prototype.getValueString = function() {
        if( this.message ) {
            return this.message;
        } else if( typeof this.value === 'object' && this.value.hasOwnProperty( 'value' ) ) {
            return mw.calculators.getValueString( this.value );
        } else {
            return String( this.value );
        }
    };
    mw.calculators.initialize();


}() );
}() );

Latest revision as of 20:55, 29 March 2022

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

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

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

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

                return units;
            }
        }
    } );

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

        return parentDrugColor;
    };

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

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

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





    /**
     * DrugPopulation
     */

    mw.calculators.drugPopulations = {};

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

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

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



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

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

        if( this.variables ) {
            for( var variableId in this.variables ) {
                if( !mw.calculators.getVariable( variableId ) ) {
                    throw new Error( 'DrugPopulation variable "' + variableId + '" not defined' );
                }

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

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

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

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

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

        return inputData;
    };

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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







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

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

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

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

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

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

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

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

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

        return searchString.trim();
    };

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





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

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

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

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

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

        drug.addDosages( drugDosageData );
    };

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



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

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

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

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

        this.color = color;

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

            this.preparations = [];

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

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

            this.dosages = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return preparations;
    };

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





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

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

        drug.addPreparations( drugPreparationData );
    };



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

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


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

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

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

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

    mw.calculators.objectClasses.DrugPreparation.prototype.toString = function() {
        return mw.calculators.getValueString( this.concentration );
    };





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

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

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

        this.indication = drugIndication;

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

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

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

        this.population = drugPopulation;

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

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

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

        drugRoutes = [];

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

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

            drugRoutes[ iRoute ] = drugRoute;
        }

        this.routes = drugRoutes;

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

        this.addDoses( drugDoseData );
    };

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

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

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

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

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

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

        inputData = inputData.merge( this.population.getCalculationData() );

        for( var iDose in this.dose ) {
            inputData = inputData.merge( this.dose[ iDose ].getCalculationData() );
        }

        return inputData;
    };

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

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

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

        return routeString;
    };

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





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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return administration;
    };

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

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

        return calculationData;
    };

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

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

}() );