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

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


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


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


                 return units;
    mw.calculators = {
        calculators: {},
        calculations: {},
        objectClasses: {},
        units: {},
        unitsBases: {},
        variables: {},
        addCalculations: function( calculationData, className ) {
            className = className ? className : DEFAULT_CALCULATION_CLASS;
 
            var calculations = mw.calculators.createCalculatorObjects( className, calculationData );
 
            for( var calculationId in calculations ) {
                 var calculation = calculations[ calculationId ];
 
                mw.calculators.calculations[ calculationId ] = calculation;
 
                mw.calculators.calculations[ calculationId ].setDependencies();
 
                mw.calculators.calculations[ calculationId ].recalculate();
            }
        },
        addCalculators: function( moduleId, calculatorData, className ) {
            className = className ? className : DEFAULT_CALCULATOR_CLASS;
 
            for( var calculatorId in calculatorData ) {
                calculatorData[ calculatorId ].module = moduleId;
            }
 
            var calculators = mw.calculators.createCalculatorObjects( className, calculatorData );
 
            if( !mw.calculators.calculators.hasOwnProperty( moduleId ) ) {
                mw.calculators.calculators[ moduleId ] = {};
            }
 
            for( var calculatorId in calculators ) {
                mw.calculators.calculators[ moduleId ][ calculatorId ] = calculators[ calculatorId ];
 
                mw.calculators.calculators[ moduleId ][ calculatorId ].render();
             }
             }
         }
         },
    } );
        addUnitsBases: function( unitsBaseData ) {
            var unitsBases = mw.calculators.createCalculatorObjects( 'UnitsBase', unitsBaseData );


    mw.calculators.addUnits( {
            for( var unitsBaseId in unitsBases ) {
        pct: {
                mw.calculators.unitsBases[ unitsBaseId ] = unitsBases[ unitsBaseId ];
            baseName: 'concentration',
             }
             definition: '10 mg/mL'
         },
         },
         vial: {
         addUnits: function( unitsData ) {
             basename: 'VOLUME'
             var units = mw.calculators.createCalculatorObjects( 'Units', unitsData );
        }
 
    } );
            for( var unitsId in units ) {
                if( mw.calculators.units.hasOwnProperty( unitsId ) ) {
                    continue;
                }


                try {
                    math.createUnit( unitsId, {
                        aliases: units[ unitsId ].aliases,
                        baseName: units[ unitsId ].baseName,
                        definition: units[ unitsId ].definition,
                        prefixes: units[ unitsId ].prefixes,
                        offset: units[ unitsId ].offset,
                    } );
                } catch( e ) {
                    console.warn( e.message );
                }


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


    /**
            for( var varId in variables ) {
    * DrugColor
                var variable = variables[ varId ];
    */
    mw.calculators.drugColors = {};


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


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


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


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


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
                if( typeof objectId === 'string' ) {
                    propertyValues.id = objectId;
                }


        if( !this.primaryColor && !this.parentColor ) {
                objects[ objectId ] = new mw.calculators.objectClasses[ className ]( propertyValues );
            throw new Error( 'Drug color "' + this.id + '" must define either a primary color or a parent color.' );
            }
        }
    };


    mw.calculators.objectClasses.DrugColor.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
            return objects;
        },
        createInputGroup: function( variableIds ) {
            var $form = $( '<form>', {


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


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


        if( !parentDrugColor ) {
            for( var iVariableId in variableIds ) {
            throw new Error( 'Parent drug color "' + this.parentColor + '" not found for drug color "' + this.id + '"' );
                var variableId = variableIds[ iVariableId ];
        }


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


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


    mw.calculators.objectClasses.DrugColor.prototype.getPrimaryColor = function() {
            return $form.append( $formRow );
         if( this.primaryColor ) {
        },
             return this.primaryColor;
         getCookieKey: function( variableId ) {
         } else if( this.parentColor ) {
             return 'calculators-var-' + variableId;
             return this.getParentDrugColor().getPrimaryColor();
         },
        }
        getCookieValue: function( varId ) {
    };
             var cookieValue = mw.cookie.get( mw.calculators.getCookieKey( varId ) );


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


            return cookieValue;
        },
        getCalculation: function( calculationId ) {
            if( mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
                return mw.calculators.calculations[ calculationId ];
            } else {
                return null;
            }
        },
        getCalculator: function( moduleId, calculatorId ) {
            if( mw.calculators.calculators.hasOwnProperty( moduleId ) &&
                mw.calculators.calculators[ moduleId ].hasOwnProperty( calculatorId ) ) {
                return mw.calculators.calculators[ moduleId ][ calculatorId ];
            } else {
                return null;
            }
        },
        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( ' ', '/' ) );
    * DrugPopulation
            }
    */


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


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


        for( var drugPopulationId in drugPopulations ) {
            if( unitsBase ) {
            mw.calculators.drugPopulations[ drugPopulationId ] = drugPopulations[ drugPopulationId ];
                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' );
            }


    mw.calculators.getDrugPopulation = function( drugPopulationId ) {
            return unitsString;
        if( mw.calculators.drugPopulations.hasOwnProperty( drugPopulationId ) ) {
        },
            return mw.calculators.drugPopulations[ drugPopulationId ];
        getValueString: function( value ) {
        } else {
            if( typeof value !== 'object' ) {
             return null;
                return null;
        }
             }
    };


            var valueString = String( value.toNumber() );


            if( value.formatUnits() ) {
                valueString += ' ' + mw.calculators.getUnitsString( value );
            }


    /**
            return valueString;
    * Class DrugPopulation
        },
    * @param {Object} propertyValues
        getVariable: function( variableId ) {
    * @returns {mw.calculators.objectClasses.DrugPopulation}
            if( mw.calculators.variables.hasOwnProperty( variableId ) ) {
    * @constructor
                return mw.calculators.variables[ variableId ];
    */
            } else {
    mw.calculators.objectClasses.DrugPopulation = function( propertyValues ) {
                 return null;
        var properties = {
            }
            required: [
        },
                 'id',
        initialize: function() {
                'name'
            math.config( {
            ],
                 number: 'BigNumber'
            optional: [
             } );
                'abbreviation',
                 'variables'
             ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
            $( '.calculator' ).each( function() {
                var gadgetModule = 'ext.gadget.calculator-' + $( this ).attr( 'data-module' );


        if( this.variables ) {
                 if( gadgetModule && mw.loader.getState( gadgetModule ) === 'registered' ) {
            for( var variableId in this.variables ) {
                     mw.loader.load( gadgetModule );
                 if( !mw.calculators.getVariable( variableId ) ) {
                     throw new Error( 'DrugPopulation variable "' + variableId + '" not defined' );
                 }
                 }
            } );
        },
        isMobile: function() {
            return window.matchMedia( 'only screen and (max-width: 760px)' ).matches;
        },
        isValueMathObject: function( value ) {
            return value && value.hasOwnProperty( 'value' );
        },
        setValue: function( variableId, value ) {
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return false;
            }


                this.variables[ variableId ].min = this.variables[ variableId ].hasOwnProperty( 'min' ) ?
            if( mw.calculators.variables[ variableId ].setValue( value ) ) {
                    math.unit( this.variables[ variableId ].min ) : null;
                mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
                    expires: COOKIE_EXPIRATION
                } );


                 this.variables[ variableId ].max = this.variables[ variableId ].hasOwnProperty( 'max' ) ?
                 return true;
                    math.unit( this.variables[ variableId ].max ) : null;
             }
             }
         } else {
 
             this.variables = {};
            return false;
         },
        uniqueValues: function( value, index, self ) {
             return self.indexOf( value ) === index;
         }
         }
     };
     };


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


    mw.calculators.objectClasses.DrugPopulation.prototype.getCalculationData = function() {
        if( properties ) {
        var inputData = new mw.calculators.objectClasses.CalculationData();
            if( properties.hasOwnProperty( 'required' ) ) {
                for( var iRequiredProperty in properties.required ) {
                    var requiredProperty = properties.required[ iRequiredProperty ];


        for( var variableId in this.variables ) {
                    if( !propertyValues || !propertyValues.hasOwnProperty( requiredProperty ) ) {
            inputData.variables.required.push( variableId );
                        console.error( 'Missing required property "' + requiredProperty + '"' );
        }
                        console.log( propertyValues );


        return inputData;
                        return null;
    };
                    }


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


        for( var variableId in this.variables ) {
                    delete propertyValues[ requiredProperty ];
            if( !dataValues.hasOwnProperty( variableId ) ) {
                 }
                 return -1;
             }
             }


             if( this.variables[ variableId ].min &&
             if( properties.hasOwnProperty( 'optional' ) ) {
                !math.largerEq( dataValues[ variableId ], this.variables[ variableId ].min ) ) {
                for( var iOptionalProperty in properties.optional ) {
                 return -1;
                    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;
                    }
                 }
             }
             }


             if( this.variables[ variableId ].max &&
            var invalidProperties = Object.keys( propertyValues );
                 !math.smallerEq( dataValues[ variableId ], this.variables[ variableId ].max ) ) {
 
                return -1;
             if( invalidProperties.length ) {
                 console.warn( 'Unsupported properties defined for ' + typeof this + ' with id "' + this.id + '": ' + invalidProperties.join( ', ' ) );
             }
             }
         }
         }
    };


         // If the data matches the population definition, the score corresponds to the number of variables in the
    mw.calculators.objectClasses.CalculatorObject.prototype.getProperties = function() {
        // population definition. This should roughly correspond to the specificity of the population.
         return {
         return Object.keys( this.variables ).length;
            required: [],
            optional: []
         };
     };
     };


     mw.calculators.objectClasses.DrugPopulation.prototype.toString = function() {
     mw.calculators.objectClasses.CalculatorObject.prototype.mergeProperties = function( inheritedProperties, properties ) {
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
         var uniqueValues = function( value, index, self ) {
    }
            return self.indexOf( value ) === index;
        };
 
        properties.required = inheritedProperties.required.concat( properties.required ).filter( uniqueValues );
        properties.optional = inheritedProperties.optional.concat( properties.optional ).filter( uniqueValues );


        return properties;
    };




Line 237: Line 348:


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


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


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


     mw.calculators.getDrugIndication = function( drugIndicationId ) {
     mw.calculators.objectClasses.Units.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        if( mw.calculators.drugIndications.hasOwnProperty( drugIndicationId ) ) {
 
            return mw.calculators.drugIndications[ drugIndicationId ];
        } else {
            return null;
        }
    };






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


         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
        if( VALID_TYPES.indexOf( this.type ) === -1 ) {
            throw new Error( 'Invalid type "' + this.type + '" for variable "' + this.id + '"' );
        }
        // Accept options as either an array of strings, or an object with ids as keys and display text as values
        if( Array.isArray( this.options ) ) {
            var options = {};
            for( var iOption in this.options ) {
                var option = this.options[ iOption ];
                options[ option ] = option;
            }
            this.options = options;
        }
        this.calculations = [];
        if( this.defaultValue ) {
            this.setValue( this.defaultValue );
        } else {
            this.value = null;
        }
     };
     };


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


     mw.calculators.objectClasses.DrugIndication.prototype.toString = function() {
     mw.calculators.objectClasses.Variable.prototype.addCalculation = function( calculationId ) {
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
         if( this.calculations.indexOf( calculationId ) !== -1 ) {
            return;
        }
 
        this.calculations.push( calculationId );
     };
     };


    mw.calculators.objectClasses.Variable.prototype.createInput = function( hideLabel ) {
        var variableId = this.id;


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


        inputContainerAttribs.class = inputContainerAttribs.class + ' calculator-container-input-' + variableId;


        // Create the input container
        var $inputContainer = $( '<div>', inputContainerAttribs );


    /**
        // Set the input id
    * Drug
        var inputId = 'calculator-input-' + variableId;
    */
    mw.calculators.drugs = {};


    mw.calculators.addDrugs = function( drugData ) {
        // Initialize label attributes
         var drugs = mw.calculators.createCalculatorObjects( 'Drug', drugData );
         var labelAttributes = {
            for: inputId,
            text: this.getLabelString()
        };


         for( var drugId in drugs ) {
         if( hideLabel ) {
             mw.calculators.drugs[ drugId ] = drugs[ drugId ];
             labelAttributes.class = 'sr-only';
         }
         }
    };


    mw.calculators.addDrugDosages = function( drugId, drugDosageData ) {
        // Create the input label and append to the container
        var drug = mw.calculators.getDrug( drugId );
        $inputContainer.append( $( '<label>', labelAttributes ) );
 
        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;
 
            // Initialize input options
            var inputAttributes = {
                id: inputId,
                class: 'form-control calculator-input-text',
                type: 'text',
                autocomplete: 'off',
                inputmode: 'decimal',
                value: this.isValueMathObject() ? this.value.toNumber() : this.value
            };
 
            // Configure additional options
            if( this.maxLength ) {
                inputAttributes.maxlength = this.maxLength;
            }
 
            // Add the input id to the list of classes
            inputAttributes.class = inputAttributes.class + ' ' + inputId;


        if( !drug ) {
            // If the variable has units, create the units input
            throw new Error( 'DrugDosage references drug "' + drugId + '" which is not defined' );
            if( this.hasUnits() ) {
        }
                // Set the units id
                unitsId = inputId + '-units';


        drug.addDosages( drugDosageData );
                var unitsValue = this.isValueMathObject() ? this.value.formatUnits() : null;


        var calculationId = 'drugDosage-' + drugId;
                // Create the units container
        var calculation = mw.calculators.getCalculation( calculationId );
                $unitsContainer = $( '<div>', {
                    class: 'input-group-append'
                } );


        if( !calculation ) {
                // Initialize the units input options
            var calculationData = {};
                var unitsInputAttributes = {
                    id: unitsId,
                    class: 'custom-select calculator-input-select'
                };


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


            mw.calculators.addCalculations( calculationData, 'DrugDosageCalculation' );
                var $unitsInput = $( '<select>', unitsInputAttributes )
                    .on( 'change', function() {
                        var newValue = $( '#' + inputId ).val() + ' ' + $( this ).val();


            calculation = mw.calculators.getCalculation( calculationId );
                        mw.calculators.setValue( variableId, newValue );
        }
                    } );


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


    mw.calculators.getDrug = function( drugId ) {
                    var unitsOptionAttributes = {
        if( mw.calculators.drugs.hasOwnProperty( drugId ) ) {
                        text: mw.calculators.getUnitsString( math.unit( '0 ' + units ) ),
            return mw.calculators.drugs[ drugId ];
                        value: units
        } else {
                    };
            return null;
        }
    };


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


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


    /**
                $unitsContainer.append( $unitsInput );
    * Class Drug
             }
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.Drug}
    * @constructor
    */
    mw.calculators.objectClasses.Drug = function( propertyValues ) {
        var properties = {
            required: [
                'id',
                'name'
             ],
            optional: [
                'color'
            ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
            // Create the input and add handlers
            var $input = $( '<input>', inputAttributes )
                .on( 'input', function() {
                    var newValue = $( this ).val();


        if( !this.color ) {
                    if( unitsId ) {
            this.color = DEFAULT_DRUG_COLOR;
                        newValue = newValue + ' ' + $( '#' + unitsId ).val();
        }
                    }


        var color = mw.calculators.getDrugColor( this.color );
                    mw.calculators.setValue( variableId, newValue );
                } );


        if( !color ) {
            // Create the input group
             throw new Error( 'Invalid drug color "' + this.color + '" for drug "' + this.id + '"' );
             var $inputGroup = $( '<div>', {
        }
                class: 'input-group'
            } ).append( $input );


        this.color = color;
            if( $unitsContainer ) {
                $inputGroup.append( $unitsContainer );
            }


         this.dosages = [];
            $inputContainer.append( $inputGroup );
        this.preparations = [];
         } else if( this.type === TYPE_STRING ) {
    };
            if( this.hasOptions() ) {
                var selectAttributes = {
                    id: inputId,
                    class: 'custom-select calculator-input-select'
                };


    mw.calculators.objectClasses.Drug.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                var $select = $( '<select>', selectAttributes )
                    .on( 'change', function() {
                        mw.calculators.setValue( variableId, $( this ).val() );
                    } );


    mw.calculators.objectClasses.Drug.prototype.addDosages = function( drugDosageData ) {
                for( var optionId in this.options ) {
        var dosages = mw.calculators.createCalculatorObjects( 'DrugDosage', drugDosageData );
                    var displayText = this.options[ optionId ];


        for( var dosageId in dosages ) {
                    var optionAttributes = {
            dosages[ dosageId ].id = this.dosages.length;
                        value: optionId,
                        text: displayText
                    };


            this.dosages.push( dosages[ dosageId ] );
                    if( optionId === this.value ) {
        }
                        optionAttributes.selected = true;
    };
                    }


    mw.calculators.objectClasses.Drug.prototype.getIndications = function() {
                    $select.append( $( '<option>', optionAttributes ) );
        var indications = [];
                }


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


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


     mw.calculators.objectClasses.Drug.prototype.getPopulations = function( indicationId ) {
     mw.calculators.objectClasses.Variable.prototype.getLabelString = function() {
         var populations = [];
         return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
    };


        for( var iDosage in this.dosages ) {
    mw.calculators.objectClasses.Variable.prototype.getValueString = function() {
            if( this.dosages[ iDosage ].population &&
        return String( this.value );
                ( !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.Variable.prototype.hasOptions = function() {
        return this.options !== null;
     };
     };


     mw.calculators.objectClasses.Drug.prototype.getPreparations = function() {
     mw.calculators.objectClasses.Variable.prototype.hasUnits = function() {
         return this.preparations.filter( mw.calculators.uniqueValues );
         return this.units !== null;
     };
     };


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


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


    mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
        if( this.type === TYPE_NUMBER ) {
            if( typeof value !== 'object' ) {
                value = math.unit( value );
            }


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


    /**
                if( !valueUnits ) {
    * DrugPreparation
                    throw new Error( 'Could not set value for "' + this.id + '": Value must define units' );
    */
                } else if( this.units.indexOf( valueUnits ) === -1 ) {
    mw.calculators.addDrugPreparations = function( drugId, drugPreparationData ) {
                    throw new Error( 'Could not set value for "' + this.id + '": Units "' + valueUnits + '" are not valid for this variable' );
        if( !mw.calculators.getDrug( drugId ) ) {
                }
            throw new Error( 'DrugPreparation references drug "' + drugId + '" which is not defined' );
            }
        } else if( this.hasOptions() ) {
            if( !this.options.hasOwnProperty( value ) ) {
                throw new Error( 'Could not set value "' + value + '" for "' + this.id + '": Value must define be one of: ' + Object.keys( this.options ).join( ', ' ) );
            }
         }
         }


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


         var drugPreparations = mw.calculators.createCalculatorObjects( 'DrugPreparation', drugPreparationData );
         for( var iCalculation in this.calculations ) {
            var calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );


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


Line 443: Line 677:


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


         mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
         this.initialize();
 
        this.concentration = math.unit( this.concentration );
     };
     };


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


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


        this.calculations.push( calculationId );
    };


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


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


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


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


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


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


         this.indication = drugIndication;
         return true;
    };


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


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


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


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


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


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


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


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


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


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


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


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


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


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


         return inputData;
         return data;
     };
     };


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


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


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


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


     /**
        this.message = null;
    * Class DrugDose
        this.value = null;
    * @param {Object} propertyValues
     };
    * @returns {mw.calculators.objectClasses.DrugDose}
 
    * @constructor
    mw.calculators.objectClasses.AbstractCalculation.prototype.isValueMathObject = function() {
    */
        return mw.calculators.isValueMathObject( this.value );
     mw.calculators.objectClasses.DrugDose = function( propertyValues ) {
    };
         mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
 
     mw.calculators.objectClasses.AbstractCalculation.prototype.recalculate = function() {
         this.message = '';
        this.value = null;
 
        var data = this.getCalculationDataValues();


         var mathProperties = this.getMathProperties();
         if( data === false ) {
            return false;
        }


         for( var iMathProperty in mathProperties ) {
         try {
             var mathProperty = mathProperties[ iMathProperty ];
             var value = this.calculate( data );


             if( this[ mathProperty ] ) {
             if( this.type === TYPE_NUMBER && !isNaN( value ) ) {
                 // TODO consider making a UnitsBase.weight.fromString()
                 if( this.units ) {
                this[ mathProperty ] = this[ mathProperty ].replace( 'kg', 'kgwt' );
                    value = value + ' ' + this.units;
                 this[ mathProperty ] = this[ mathProperty ].replace( 'mcg', 'ug' );
                 }


                 this[ mathProperty ] = math.unit( this[ mathProperty ] )
                 this.value = math.unit( value );
             } else {
             } else {
                 this[ mathProperty ] = null;
                 this.value = value;
            }
 
            for( var iCalculation in this.calculations ) {
                calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );
 
                if( calculation ) {
                    calculation.render();
                }
             }
             }
        } catch( e ) {
            this.message = e.message;
            this.value = null;
         }
         }


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


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


             this.weightCalculation = weightCalculation;
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
        this.recalculate();
 
        if( typeof this.onRender === 'function' ) {
             this.onRender();
        }
 
        this.doRender();
 
        if( typeof this.onRendered === 'function' ) {
            this.onRendered();
         }
         }
     };
     };


     mw.calculators.objectClasses.DrugDose.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
     mw.calculators.objectClasses.AbstractCalculation.prototype.setDependencies = function() {
        var calculationData = this.getCalculationData();


    mw.calculators.objectClasses.DrugDose.prototype.getCalculationData = function() {
        var calculationIds = calculationData.calculations.required.concat( calculationData.calculations.optional );
        var calculationData = new mw.calculators.objectClasses.CalculationData();


         var mathProperties = this.getMathProperties();
         for( var iCalculationId in calculationIds ) {
            var calculationId = calculationIds[ iCalculationId ];


        // Look at dose properties to identify any variable dependence (e.g. weight-dependence)
            if( !mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
        for( var iMathProperty in mathProperties ) {
                throw new Error('Calculation "' + calculationId + '" does not exist for calculation "' + this.id + '"');
            var mathProperty = mathProperties[ iMathProperty ];
            }
 
            mw.calculators.calculations[ calculationId ].addCalculation( this.id );
        }
 
        var variableIds = calculationData.variables.required.concat( calculationData.variables.optional );


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


            // For now, this only supports weight dependence, unclear if it will need to be more generalizable in the future
             if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
             if( mw.calculators.isValueDependent( dosePropertyValue, 'weight' ) &&
                 throw new Error('Variable "' + variableId + '" does not exist for calculation "' + this.id + '"');
                calculationData.variables.optional.indexOf( 'weight' ) === -1 ) {
                 calculationData.variables.optional.push( 'weight' );
             }
             }
        }


        if( this.weightCalculation ) {
             mw.calculators.variables[ variableId ].addCalculation( this.id );
             calculationData.calculations.optional.push( this.weightCalculation.id );
         }
         }
        return calculationData;
     };
     };


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


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


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






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


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


    mw.calculators.objectClasses.DrugDosageCalculation.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculation.prototype );
        for( var iDataType in dataTypes ) {
            var dataType = dataTypes[ iDataType ];


    mw.calculators.objectClasses.DrugDosageCalculation.prototype.calculate = function( data ) {
            if( !this[ dataType ] ) {
        var value = {
                this[ dataType ] = {
            population: null,
                    optional: [],
            dose: []
                    required: []
        };
                };
 
            } else {
        // Determine which dosage to use
                this[ dataType ].optional = this[ dataType ].hasOwnProperty( 'optional' ) ? this[ dataType ].optional : [];
        var populationScores = [];
                this[ dataType ].required = this[ dataType ].hasOwnProperty( 'required' ) ? this[ dataType ].required : [];
 
             }
        for( var iDosage in data.drug.dosages ) {
            var drugDosage = data.drug.dosages[ iDosage ];
 
            // If the indication does not match, set the score to -1
            var populationScore = ( drugDosage.indication.id === data.indication.id ) ?
                drugDosage.population.getCalculationDataScore( data ) : -1;
 
             populationScores.push( populationScore );
         }
         }
    };


        var maxPopulationScore = Math.max.apply( null, populationScores );
    mw.calculators.objectClasses.CalculationData.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );


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


        // If there is more than one dosage with the same score, take the first.
    mw.calculators.objectClasses.CalculationData.prototype.getProperties = function() {
        // This allows the data editor to decide which is most important.
        return {
        var dosageId = populationScores.indexOf( maxPopulationScore );
            required: [],
 
            optional: [
        var dosage = data.drug.dosages[ dosageId ];
                'calculations',
                'variables'
            ]
        };
    };


        value.population = dosage.population;


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


            // Initialize value properties for dose
    mw.calculators.objectClasses.CalculationData.prototype.merge = function() {
            value.dose[ iDose ] = {
        var mergedData = new mw.calculators.objectClasses.CalculationData();
                massPerWeight: {},
                mass: {},
                name: dose.name,
                volume: {},
                weightCalculation: dose.weightCalculation ? dose.weightCalculation : null
            };


            var weightValue = dose.weightCalculation ? dose.weightCalculation.value : data.weight;
        var data = [ this ].concat( Array.prototype.slice.call( arguments ) );


            for( var iMathProperty in mathProperties ) {
        var dataTypes = this.getDataTypes();
                var mathProperty = mathProperties[ iMathProperty ];


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


                 if( doseValue ) {
                 mergedData[ dataType ].required = mergedData[ dataType ].required
                     if( mw.calculators.isValueDependent( doseValue, 'weight' ) ) {
                    .concat( data[ iData ][ dataType ].required )
                        value.dose[ iDose ].massPerWeight[ mathProperty ] = doseValue;
                     .filter( mw.calculators.uniqueValues );


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


         return value;
         return mergedData;
     };
     };


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


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


        $calculationContainer.empty();


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


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


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


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


        var indicationHtml = '';


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


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


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


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


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


             if( !$.isEmptyObject( doseValue.massPerWeight ) ) {
             labelHtml = $( '<a>', {
                 if( doseValue.massPerWeight.hasOwnProperty( 'dose' ) ) {
                 href: href,
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.dose );
                text: labelHtml
                } else if( doseValue.massPerWeight.hasOwnProperty( 'min' ) &&
            } )[ 0 ].outerHTML;
                    doseValue.massPerWeight.hasOwnProperty( 'max' ) ) {
        }
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.min );
 
                    dosageHtml += '-';
        return labelHtml;
                    dosageHtml += mw.calculators.getValueString( doseValue.massPerWeight.max );
    };
                }
 
    mw.calculators.objectClasses.SimpleCalculation.prototype.getLabelString = function() {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
    };


                if( doseValue.weightCalculation ) {
    mw.calculators.objectClasses.SimpleCalculation.prototype.getProperties = function() {
                    dosageHtml += ' (' + doseValue.weightCalculation.getLabelString() + ')';
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();
                }


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


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


                dosageHtml += '<br />';
            var digits = ( this.value.formatUnits() === units && this.digits !== null ) ? this.digits : 1;
            }


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


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


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


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


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


        var valueString = this.getValueString();


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


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


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


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


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


            var $infoButton = null;


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


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


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


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


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


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


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


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


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


        data.drug = this.drug;


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


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


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


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


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


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


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


         this.drug = drug;
         this.doRender();
 
        var variableIds = this.getVariableIds();


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


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


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




Line 1,091: Line 1,289:


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


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


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


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


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


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


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


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


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


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


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


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


}() );
}() );

Revision as of 10:48, 11 August 2021

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

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

    var VALID_TYPES = [
        TYPE_NUMBER,
        TYPE_STRING
    ];

    var DEFAULT_CALCULATION_CLASS = 'SimpleCalculation';
    var DEFAULT_CALCULATOR_CLASS = 'SimpleCalculator';

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

        return null;
    };


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

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

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

                mw.calculators.calculations[ calculationId ] = calculation;

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

                mw.calculators.calculations[ calculationId ].recalculate();
            }
        },
        addCalculators: function( moduleId, calculatorData, className ) {
            className = className ? className : DEFAULT_CALCULATOR_CLASS;

            for( var calculatorId in calculatorData ) {
                calculatorData[ calculatorId ].module = moduleId;
            }

            var calculators = mw.calculators.createCalculatorObjects( className, calculatorData );

            if( !mw.calculators.calculators.hasOwnProperty( moduleId ) ) {
                mw.calculators.calculators[ moduleId ] = {};
            }

            for( var calculatorId in calculators ) {
                mw.calculators.calculators[ moduleId ][ calculatorId ] = calculators[ calculatorId ];

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

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

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

                try {
                    math.createUnit( unitsId, {
                        aliases: units[ unitsId ].aliases,
                        baseName: units[ unitsId ].baseName,
                        definition: units[ unitsId ].definition,
                        prefixes: units[ unitsId ].prefixes,
                        offset: units[ unitsId ].offset,
                    } );
                } catch( e ) {
                    console.warn( e.message );
                }

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

            for( var varId in variables ) {
                var variable = variables[ varId ];

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

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

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

            var objects = {};

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

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

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

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

            } );

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

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

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

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

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

            if( !cookieValue ) {
                return null;
            }

            return cookieValue;
        },
        getCalculation: function( calculationId ) {
            if( mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
                return mw.calculators.calculations[ calculationId ];
            } else {
                return null;
            }
        },
        getCalculator: function( moduleId, calculatorId ) {
            if( mw.calculators.calculators.hasOwnProperty( moduleId ) &&
                mw.calculators.calculators[ moduleId ].hasOwnProperty( calculatorId ) ) {
                return mw.calculators.calculators[ moduleId ][ calculatorId ];
            } else {
                return null;
            }
        },
        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 ) {
                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;
        },
        getValueString: function( value ) {
            if( typeof value !== 'object' ) {
                return null;
            }

            var valueString = String( value.toNumber() );

            if( value.formatUnits() ) {
                valueString += ' ' + mw.calculators.getUnitsString( value );
            }

            return valueString;
        },
        getVariable: function( variableId ) {
            if( mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return mw.calculators.variables[ variableId ];
            } else {
                return null;
            }
        },
        initialize: function() {
            math.config( {
                number: 'BigNumber'
            } );

            $( '.calculator' ).each( function() {
                var gadgetModule = 'ext.gadget.calculator-' + $( this ).attr( 'data-module' );

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

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

                return true;
            }

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

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

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

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

                        return null;
                    }

                    this[ requiredProperty ] = propertyValues[ requiredProperty ];

                    delete propertyValues[ requiredProperty ];
                }
            }

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

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

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

            var invalidProperties = Object.keys( propertyValues );

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

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

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

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

        return properties;
    };




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

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

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




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

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

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




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

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

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

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

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

                options[ option ] = option;
            }

            this.options = options;
        }

        this.calculations = [];

        if( this.defaultValue ) {
            this.setValue( this.defaultValue );
        } else {
            this.value = null;
        }
    };

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

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

        this.calculations.push( calculationId );
    };

    mw.calculators.objectClasses.Variable.prototype.createInput = function( hideLabel ) {
        var variableId = this.id;

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

        inputContainerAttribs.class = inputContainerAttribs.class + ' calculator-container-input-' + variableId;

        // Create the input container
        var $inputContainer = $( '<div>', inputContainerAttribs );

        // Set the input id
        var inputId = 'calculator-input-' + variableId;

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

        if( hideLabel ) {
            labelAttributes.class = 'sr-only';
        }

        // Create the input label and append to the container
        $inputContainer.append( $( '<label>', labelAttributes ) );

        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;

            // Initialize input options
            var inputAttributes = {
                id: inputId,
                class: 'form-control calculator-input-text',
                type: 'text',
                autocomplete: 'off',
                inputmode: 'decimal',
                value: this.isValueMathObject() ? this.value.toNumber() : this.value
            };

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

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

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

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

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

                // Initialize the units input options
                var unitsInputAttributes = {
                    id: unitsId,
                    class: 'custom-select calculator-input-select'
                };

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

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

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

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

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

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

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

                $unitsContainer.append( $unitsInput );
            }

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

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

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

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

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

            $inputContainer.append( $inputGroup );
        } else if( this.type === TYPE_STRING ) {
            if( this.hasOptions() ) {
                var selectAttributes = {
                    id: inputId,
                    class: 'custom-select calculator-input-select'
                };

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

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

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

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

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

                $inputContainer.append( $select );
            }
        }

        return $inputContainer;
    };

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

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

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

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

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

        return true;
    };

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

    mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
        if( this.type === TYPE_NUMBER ) {
            if( typeof value !== 'object' ) {
                value = math.unit( value );
            }

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

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

        this.value = value;

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

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

        return true;
    };



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

        this.initialize();
    };

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

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

        this.calculations.push( calculationId );
    };

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

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

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

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

        return this.value;
    };

    mw.calculators.objectClasses.AbstractCalculation.prototype.hasInfo = function() {
        return false;
    };

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

        return true;
    };

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

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

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

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

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

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

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

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

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

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

            return false;
        }

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

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

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

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

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

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

        return data;
    };

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

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

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

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

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

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

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

        var data = this.getCalculationDataValues();

        if( data === false ) {
            return false;
        }

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

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

                this.value = math.unit( value );
            } else {
                this.value = value;
            }

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

                if( calculation ) {
                    calculation.render();
                }
            }
        } catch( e ) {
            this.message = e.message;
            this.value = null;
        }

        return true;
    };



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

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

        this.doRender();

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

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

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

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

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

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

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

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

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

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



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



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

        var dataTypes = this.getDataTypes();

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

            if( !this[ dataType ] ) {
                this[ dataType ] = {
                    optional: [],
                    required: []
                };
            } else {
                this[ dataType ].optional = this[ dataType ].hasOwnProperty( 'optional' ) ? this[ dataType ].optional : [];
                this[ dataType ].required = this[ dataType ].hasOwnProperty( 'required' ) ? this[ dataType ].required : [];
            }
        }
    };

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

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

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



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

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

        var dataTypes = this.getDataTypes();

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

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

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

        return mergedData;
    };





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

        this.initialize();
    };

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


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

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

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

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

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

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

        return labelHtml;
    };

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

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

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

    mw.calculators.objectClasses.SimpleCalculation.prototype.getValueString = function() {
        if( this.message ) {
            return this.message;
        } else if( typeof this.value === 'object' && this.value.hasOwnProperty( 'value' ) ) {
            // format() will convert the value to the most visually appealing units (e.g. 5200 mL becomes 5.2 L)
            // We then want to turn that back into a math object.
            var value = math.unit( this.value.format() );
            var units = value.formatUnits();
            var number = value.toNumber();

            var digits = ( this.value.formatUnits() === units && this.digits !== null ) ? this.digits : 1;

            var valueString = String( number.toFixed( digits ) );

            if( units ) {
                valueString = valueString + ' ' + mw.calculators.getUnitsString( value );
            }

            return valueString;
        } else {
            return String( this.value );
        }
    };

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

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

        var valueString = this.getValueString();

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

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

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

        var calculation = this;

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

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

            var $infoButton = null;

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

            var labelHtml = calculation.getLabelHtml();

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

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

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

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

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

                    var api = new mw.Api();

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

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

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

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

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

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

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

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

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

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

                $( this ).after( $variablesContainer );

                missingVariableInputs = [];
            }
        } );
    };





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

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

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

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

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

        this.doRender();

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


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





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

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


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

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

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

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

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

        $calculatorContainer.empty();

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

        var $calculationsContainer;

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

        $calculatorContainer.append( $calculationsContainer );

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

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

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

                $calculationsContainer.append( $calculationContainer );
            }

            calculation.render();
        }
    };

    mw.calculators.initialize();

}() );