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

From WikiAnesthesia
Line 1: Line 1:
/**
* @author Chris Rishel
*/
( function() {
( function() {
     var COOKIE_EXPIRATION = 12 * 60 * 60;
     var moduleId = 'anatomyPhysiology';


     var TYPE_NUMBER = 'number';
     mw.calculators.addUnitsBases( {
    var TYPE_STRING = 'string';
        bpm: {
            toString: function( units ) {
                units = units.replace( 'bpm', 'beats/min' );


    var VALID_TYPES = [
                 return units;
        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;
             }
             }
         }
         },
 
         hgb: {
        return null;
            toString: function( units ) {
    };
                units = units.replace( 'hgbperdL', '/dL' );
 
                 units = units.replace( 'pcthct', '%' );
 
    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();
                 return units;
             }
             }
         },
         },
         addCalculators: function( moduleId, calculatorData, className ) {
         o2: {
             className = className ? className : DEFAULT_CALCULATOR_CLASS;
             toString: function( units ) {
 
                 units = units.replace( 'pcto2', '%' );
            for( var calculatorId in calculatorData ) {
                 calculatorData[ calculatorId ].module = moduleId;
 
                // Make sure the calculations have been defined
                for( var iCalculation in calculatorData[ calculatorId ].calculations ) {
                    var calculationId = calculatorData[ calculatorId ].calculations[ iCalculation ];


                    if( !mw.calculators.getCalculation( calculationId ) ) {
                return units;
                        throw new Error( 'Calculator "' + calculatorId + '" references calculation "' + calculationId + '" which is not defined' );
                    }
                }
             }
             }
        },
        temperature: {
            toString: function( units ) {
                units = units.replace( 'deg', '°' );


            var calculators = mw.calculators.createCalculatorObjects( className, calculatorData );
                 return units;
 
            // Initalize the calculators property for the module
            if( !mw.calculators.calculators.hasOwnProperty( moduleId ) ) {
                 mw.calculators.calculators[ moduleId ] = {};
             }
             }
        }
    } );


            // Store the calculators
    mw.calculators.addUnits( {
             for( var calculatorId in calculators ) {
        bpm: {
                mw.calculators.calculators[ moduleId ][ calculatorId ] = calculators[ calculatorId ];
             basename: 'bpm'
 
        },
                mw.calculators.calculators[ moduleId ][ calculatorId ].render();
        pcthct: {
             }
            baseName: 'hgb'
        },
        pcto2: {
             baseName: 'o2'
         },
         },
         addUnitsBases: function( unitsBaseData ) {
         ghgbperdL: {
             var unitsBases = mw.calculators.createCalculatorObjects( 'UnitsBase', unitsBaseData );
             baseName: 'hgb',
            prefixes: 'short',
            definition: '3 pcthct'
        }
    } );


            for( var unitsBaseId in unitsBases ) {
    mw.calculators.addVariables( {
                mw.calculators.unitsBases[ unitsBaseId ] = unitsBases[ unitsBaseId ];
        caseDuration: {
             }
            name: 'Case duration',
            type: 'number',
            abbreviation: 'Duration',
            maxLength: 3,
            units: [
                'hr',
                'min'
             ]
         },
         },
         addUnits: function( unitsData ) {
         hct: {
             var units = mw.calculators.createCalculatorObjects( 'Units', unitsData );
             name: 'Current hematocrit',
 
             type: 'number',
             for( var unitsId in units ) {
            abbreviation: 'Current hct',
                if( mw.calculators.units.hasOwnProperty( unitsId ) ) {
            defaultValue: '45 pcthct',
                    continue;
            maxLength: 4,
                }
            units: [
 
                'pcthct',
                try {
                 'ghgbperdL'
                    var unitData = {
            ]
                        aliases: units[ unitsId ].aliases,
                        baseName: units[ unitsId ].baseName ? units[ unitsId ].baseName.toUpperCase() : units[ unitsId ].baseName,
                        definition: units[ unitsId ].definition,
                        prefixes: units[ unitsId ].prefixes,
                        offset: units[ unitsId ].offset,
                    };
 
                    math.createUnit( unitsId, unitData );
                 } catch( e ) {
                    console.warn( e.message );
                }
 
                mw.calculators.units[ units ] = units[ unitsId ];
            }
         },
         },
         addVariables: function( variableData ) {
         heartRate: {
             var variables = mw.calculators.createCalculatorObjects( 'Variable', variableData );
             name: 'Heart rate',
 
            type: 'number',
             for( var variableId in variables ) {
             abbreviation: 'HR',
                mw.calculators.variables[ variableId ] = variables[ variableId ];
            defaultValue: '60 bpm',
 
            maxLength: 4,
                var cookieValue = mw.calculators.getCookieValue( variableId );
            units: [
 
                 'bpm'
                if( cookieValue ) {
             ]
                    try {
                        // isValueValid will throw an error if invalid, so the catch clause is our else condition
                        if( mw.calculators.variables[ variableId ].isValueValid( cookieValue ) ) {
                            mw.calculators.variables[ variableId ].setValue( cookieValue );
                        }
                    } catch( e ) {
                        // Unset the cookie value since for whatever reason it's no longer valid.
                        mw.calculators.setCookieValue( variableId, null );
                    }
                 }
             }
         },
         },
         createCalculatorObjects: function( className, objectData ) {
         hgb: {
             if( !mw.calculators.objectClasses.hasOwnProperty( className ) ) {
             name: 'Hemoglobin',
                throw new Error( 'Invalid class name "' + className + '"' );
            type: 'number',
             }
            abbreviation: 'HgB',
 
             defaultValue: '13 ghgbperdL',
             var objects = {};
             maxLength: 4,
 
             units: [
             for( var objectId in objectData ) {
                 'pcthct',
                var propertyValues = objectData[ objectId ];
                 'ghgbperdL'
 
            ]
                 // Id can either be specified using the 'id' property, or as the property name in objectData
                 if( propertyValues.hasOwnProperty( 'id' ) ) {
                    objectId = propertyValues.id;
                }
                else {
                    propertyValues.id = objectId;
                }
 
                objects[ objectId ] = new mw.calculators.objectClasses[ className ]( propertyValues );
            }
 
            return objects;
         },
         },
         createInputGroup: function( variableIds ) {
         minHct: {
             var $form = $( '<form>', {
             name: 'Minimum hematocrit',
 
             type: 'number',
             } );
            abbreviation: 'Min hct',
 
             defaultValue: '21 pcthct',
            var $formRow = $( '<div>', {
            maxLength: 4,
                class: 'form-row'
             units: [
             } ).css( 'flex-wrap', 'nowrap' );
                 'pcthct',
 
                'ghgbperdL'
             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 ) {
         paCO2: {
             return 'calculators-var-' + variableId;
             name: 'PaCO<sub>2</sub>',
            type: 'number',
            abbreviation: 'PaCO<sub>2</sub>',
            defaultValue: '40 mmHg',
            maxLength: 3,
            units: [
                'mmHg'
            ]
         },
         },
         getCookieValue: function( varId ) {
         saO2: {
             var cookieValue = mw.cookie.get( mw.calculators.getCookieKey( varId ) );
             name: 'SaO<sub>2</sub>',
 
            type: 'number',
             if( !cookieValue ) {
             abbreviation: 'SaO<sub>2</sub>',
                return null;
            defaultValue: '100 pcto2',
             }
            maxLength: 3,
 
             units: [
             return cookieValue;
                'pcto2'
             ]
         },
         },
         getCalculation: function( calculationId ) {
         smvO2: {
             if( mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
             name: 'SmvO<sub>2</sub>',
                return mw.calculators.calculations[ calculationId ];
            type: 'number',
             } else {
            abbreviation: 'SmvO<sub>2</sub>',
                 return null;
            defaultValue: '75 pcto2',
             }
            maxLength: 3,
             units: [
                 'pcto2'
             ]
         },
         },
         getCalculator: function( moduleId, calculatorId ) {
         npoTime: {
             if( mw.calculators.calculators.hasOwnProperty( moduleId ) &&
            name: 'Time spent NPO',
                mw.calculators.calculators[ moduleId ].hasOwnProperty( calculatorId ) ) {
            type: 'number',
                return mw.calculators.calculators[ moduleId ][ calculatorId ];
             abbreviation: 'NPO time',
             } else {
            defaultValue: '8 hr',
                 return null;
            maxLength: 2,
             }
             units: [
                 'hr'
             ]
         },
         },
         getUnitsByBase: function( value ) {
         surgicalTrauma: {
             if( typeof value !== 'object' || !value.hasOwnProperty( 'units' ) ) {
             name: 'Severity of surgical trauma',
                return null;
            type: 'string',
             }
             abbreviation: 'Surgical trauma',
 
             defaultValue: 'Minimal',
             var unitsByBase = {};
             options: [
 
                 'Minimal',
             for( var iUnits in value.units ) {
                'Moderate',
                 var units = value.units[ iUnits ];
                 'Severe'
 
             ]
                 unitsByBase[ units.unit.base.key.toLowerCase() ] = units.prefix.name + units.unit.name;
             }
 
            return unitsByBase;
         },
         },
         getUnitsString: function( value ) {
         temperature: {
             if( typeof value !== 'object' ) {
             name: 'Temperature',
                return null;
             type: 'number',
             }
             abbreviation: 'Temp',
 
             defaultValue: '37 degC',
             var unitsString = value.formatUnits();
             maxLength: 5,
 
             units: [
             var reDenominator = /\/\s?\((.*)\)/;
                 'degC',
             var denominatorMatches = unitsString.match( reDenominator );
                'degF'
 
             ]
             if( denominatorMatches ) {
        }
                var denominatorUnits = denominatorMatches[ 1 ];
    } );
 
                 unitsString = unitsString.replace( reDenominator, '/' + denominatorUnits.replace( ' ', '/' ) );
             }
 
            unitsString = unitsString
                .replace( /\s/g, '' )
                .replace( /(\^(\d+))/g, '<sup>$2</sup>' );


            var unitsBase = value.getBase();


            if( unitsBase ) {
                unitsBase = unitsBase.toLowerCase();


                if( mw.calculators.unitsBases.hasOwnProperty( unitsBase ) &&
    mw.calculators.addCalculations( {
                    typeof mw.calculators.unitsBases[ unitsBase ].toString === 'function' ) {
        bmi: {
                     unitsString = mw.calculators.unitsBases[ unitsBase ].toString( unitsString );
            name: 'Body mass index',
            abbreviation: 'BMI',
            data: {
                variables: {
                     required: [ 'weight', 'height' ]
                 }
                 }
             } else {
             },
                // TODO nasty hack to fix weight units in compound units which have no base
            digits: 0,
                unitsString = unitsString.replace( 'kgwt', 'kg' );
            units: 'kg/m^2',
                 unitsString = unitsString.replace( 'ug', 'mcg' );
            formula: '<math>\\mathrm{BMI} = \\frac{\\mathrm{mass_{kg}}}{{\\mathrm{height_{m}}}^2}</math>',
            link: '[[Body mass index]]',
            references: [],
            calculate: function( data ) {
                 return data.weight.toNumber( 'kgwt' ) / Math.pow( data.height.toNumber( 'm' ), 2 );
             }
             }
            return unitsString;
         },
         },
         getValueDecimals: function( value ) {
         bsa: {
             // Supports either numeric values or math objects
             name: 'Body surface area',
             if( mw.calculators.isValueMathObject( value ) ) {
            abbreviation: 'BSA',
                 value = mw.calculators.getValueNumber( value );
             data: {
             }
                variables: {
 
                    required: [ 'weight', 'height' ]
             if( typeof value !== 'number' ) {
                 }
                return null;
             },
             }
            digits: 2,
 
             units: 'm^2',
             // Convert the number to a string, reverse, and count the number of characters up to the period.
             formula: '<math>\\mathrm{BSA} = \\sqrt{\\frac{\\mathrm{weight_{kg}}*\\mathrm{height_{cm}}}{3600}}</math>',
             var decimals = value.toString().split('').reverse().join('').indexOf( '.' );
             link: false,
 
             references: [
             // If no decimal is present, will be set to -1 by indexOf. If so, set to 0.
                'Mosteller RD. Simplified calculation of body-surface area. N Engl J Med. 1987 Oct 22;317(17):1098. doi: 10.1056/NEJM198710223171717. PMID: 3657876.'
             decimals = decimals > 0 ? decimals : 0;
             ],
 
             calculate: function( data ) {
            return decimals;
                 return Math.sqrt( data.height.toNumber( 'cm' ) * data.weight.toNumber( 'kgwt' ) / 3600 );
        },
        getValueNumber: function( value, decimals ) {
            if( typeof value !== 'object' ) {
                 return null;
            }
 
            // Remove floating point errors
            var number = math.round( value.toNumber(), 10 );
 
            var absNumber = math.abs( number );
 
            if( absNumber >= 10 ) {
                decimals = 0;
            } else {
                decimals = -math.floor( math.log10( absNumber ) ) + 1;
             }
             }
            return math.round( number, decimals );
         },
         },
         getValueString: function( value, decimals ) {
         ebv: {
             if( !mw.calculators.isValueMathObject( value ) ) {
             name: 'Estimated blood volume',
                return null;
             abbreviation: 'EBV',
             }
             data: {
 
                 variables: {
            var valueNumber = mw.calculators.getValueNumber( value, decimals );
                    required: [ 'weight', 'age' ]
             var valueUnits = mw.calculators.getUnitsString( value );
 
            if( math.abs( math.log10( valueNumber ) ) > 3 ) {
                 var valueUnitsByBase = mw.calculators.getUnitsByBase( value );
 
                var oldSIUnit;
 
                if( valueUnitsByBase.hasOwnProperty( 'mass' ) ) {
                    oldSIUnit = valueUnitsByBase.mass;
                } else if( valueUnitsByBase.hasOwnProperty( 'volume' ) ) {
                    oldSIUnit = valueUnitsByBase.volume;
                 }
                 }
            },
            digits: 0,
            units: 'mL',
            formula: '',
            references: [
                'Morgan & Mikhail\'s Clinical Anesthesiology. 5e. p1168'
            ],
            calculate: function( data ) {
                var weight = data.weight.toNumber( 'kgwt' );
                var age = data.age.toNumber( 'yo' );


                 if( oldSIUnit ) {
                 var ebvPerKg;
                    // This new value should simplify to the optimal SI prefix.
                    // We need to create a completely new unit from the formatted (i.e. simplified) value
                    var newSIValue = math.unit( math.unit( valueNumber + ' ' + oldSIUnit ).format() );


                    // There is a bug in mathjs where formatUnits() won't simplify the units, only format() will.
                if( age >= 1 ) {
                    var newSIUnit = newSIValue.formatUnits();
                     if( data.gender === 'F' ) {
 
                         ebvPerKg = 65;
                     if( newSIUnit !== oldSIUnit ) {
                    } else {
                        var newValue = math.unit( newSIValue.toNumber() + ' ' + value.formatUnits().replace( oldSIUnit, newSIUnit ) );
                         ebvPerKg = 75;
 
                         valueNumber = mw.calculators.getValueNumber( newValue, decimals );
                         valueUnits = mw.calculators.getUnitsString( newValue );
                     }
                     }
                } else if( age >= 1/12 ) {
                    ebvPerKg = 80;
                } else if( age >= 0 ) {
                    ebvPerKg = 85;
                } else {
                    ebvPerKg = 95;
                 }
                 }
            }
            var valueString = String( valueNumber );
            if( valueUnits ) {
                valueString += ' ' + valueUnits;
            }


            return valueString;
                 return weight * ebvPerKg;
        },
        getVariable: function( variableId ) {
            if( mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return mw.calculators.variables[ variableId ];
            } else {
                return null;
            }
        },
        hasData: function( dataType, dataId ) {
            if( mw.calculators.hasOwnProperty( dataType ) &&
                mw.calculators[ dataType ].hasOwnProperty( dataId ) ) {
                return true;
            } else {
                 return false;
             }
             }
         },
         },
         initialize: function() {
         fluidMaintenanceRate: {
             $( '.calculator' ).each( function() {
             name: 'Fluid maintenance rate',
                var gadgetModule = 'ext.gadget.calculator-' + $( this ).attr( 'data-module' );
            abbreviation: 'Fluid maint.',
 
            data: {
                 if( gadgetModule && mw.loader.getState( gadgetModule ) === 'registered' ) {
                 variables: {
                     mw.loader.load( gadgetModule );
                     required: [ 'weight' ]
                 }
                 }
             } );
             },
        },
            digits: 0,
        isMobile: function() {
             units: 'mL/hr',
             return window.matchMedia( 'only screen and (max-width: 760px)' ).matches;
            formula: '',
        },
            references: [
        isValueMathObject: function( value ) {
                 'Miller\'s Anesthesia 7e, section IV, pg. 1728'
            return value && value.hasOwnProperty( 'value' );
             ],
        },
             calculate: function( data ) {
        setCookieValue: function( variableId, value ) {
                var weight = data.weight.toNumber( 'kgwt' );
            mw.cookie.set( mw.calculators.getCookieKey( variableId ), value, {
                 expires: COOKIE_EXPIRATION
            } );
        },
        setValue: function( variableId, value ) {
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                return false;
             }
 
            if( mw.calculators.variables[ variableId ].setValue( value ) ) {
                mw.calculators.setCookieValue( variableId, value );
 
                return true;
             }
 
            return false;
        },
        uniqueValues: function( value, index, self ) {
            return self.indexOf( value ) === index;
        }
    };


    /**
                // Uses 4-2-1 rule
    * Class CalculatorObject
                var maintenanceRate = 4 * Math.min( weight, 10 );
    *
    * @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( weight > 10 ) {
            if( properties.hasOwnProperty( 'required' ) ) {
                     maintenanceRate += 2 * Math.min( weight - 10, 10 );
                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 ];
                if( weight > 20) {
                    } else if( typeof this[ optionalProperty ] === 'undefined' ) {
                    maintenanceRate += weight - 20;
                        this[ optionalProperty ] = null;
                    }
                 }
                 }
            }
            var invalidProperties = Object.keys( propertyValues );


            if( invalidProperties.length ) {
                 return maintenanceRate;
                 console.warn( 'Unsupported properties defined for ' + typeof this + ' with id "' + this.id + '": ' + invalidProperties.join( ', ' ) );
             }
             }
         }
         },
    };
        intraopFluids: {
 
            name: 'Intraoperative fluid dosing',
    mw.calculators.objectClasses.CalculatorObject.prototype.getProperties = function() {
            abbreviation: 'Intraop fluids',
        return {
            data: {
            required: [],
                calculations: {
            optional: []
                    required: [ 'fluidMaintenanceRate' ]
        };
                },
    };
                variables: {
 
                    required: [ 'weight', 'npoTime', 'surgicalTrauma' ]
    mw.calculators.objectClasses.CalculatorObject.prototype.mergeProperties = function( inheritedProperties, properties ) {
                }
        var uniqueValues = function( value, index, self ) {
            },
             return self.indexOf( value ) === index;
            type: 'string',
        };
             references: [
 
                'Corcoran T, Rhodes JE, Clarke S, Myles PS, Ho KM. Perioperative fluid management strategies in major surgery: a stratified meta-analysis. Anesth Analg. 2012 Mar;114(3):640-51. doi: 10.1213/ANE.0b013e318240d6eb. Epub 2012 Jan 16. PMID: 22253274.'
        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: [
             calculate: function( data ) {
                 'toString'
                 var weight = data.weight.toNumber( 'kgwt' );
            ]
                var maintenanceRate = data.fluidMaintenanceRate.toNumber( 'mL/hr' );
        };
                var npoTime = data.npoTime.toNumber( 'hr' );
                var surgicalTrauma = data.surgicalTrauma;


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
                var output = '';
    };


    mw.calculators.objectClasses.UnitsBase.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                var npoDeficit = npoTime * maintenanceRate;


                var surgicalLossMin, surgicalLossMax;


                if( surgicalTrauma === 'Minimal' ) {
                    surgicalLossMin = 2 * weight;
                    surgicalLossMax = 4 * weight;
                } else if( surgicalTrauma === 'Moderate' ) {
                    surgicalLossMin = 4 * weight;
                    surgicalLossMax = 6 * weight;
                } else {
                    surgicalLossMin = 6 * weight;
                    surgicalLossMax = 8 * weight;
                }


                var firstHour = Math.round( npoDeficit / 2 ) + maintenanceRate;
                var nextHoursMin = Math.round( npoDeficit / 4 ) + maintenanceRate + surgicalLossMin;
                var nextHoursMax = Math.round( npoDeficit / 4 ) + maintenanceRate + surgicalLossMax;
                var remainingHoursMin = maintenanceRate + surgicalLossMin;
                var remainingHoursMax = maintenanceRate + surgicalLossMax;


    /**
                output += 'NPO deficit: ' + Math.round( npoDeficit ) + ' mL<br/>';
    * Class Units
                output += 'Surgical losses: ' + surgicalLossMin + '-' + surgicalLossMax + ' mL/hr<br/>';
    * @param {Object} propertyValues
                 output += '1st hour: ' + firstHour + ' mL<br/>';
    * @returns {mw.calculators.objectClasses.Units}
                output += '2nd hour: ' + nextHoursMin + '-' + nextHoursMax + ' mL<br/>';
    * @constructor
                 output += '3rd hour: ' + nextHoursMin + '-' + nextHoursMax + ' mL<br/>';
    */
                 output += '4+ hours: ' + remainingHoursMin + '-' + remainingHoursMax + ' mL<br/>';
    mw.calculators.objectClasses.Units = function( propertyValues ) {
        var properties = {
            required: [
                 'id'
            ],
            optional: [
                 'aliases',
                'baseName',
                 'definition',
                'offset',
                'prefixes'
            ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
                return output;
    };
            }
 
        },
    mw.calculators.objectClasses.Units.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        maxAbl: {
 
            name: 'Maximum allowable blood loss',
 
            abbreviation: 'Max ABL',
 
            data: {
 
                calculations: {
    /**
                    required: [ 'ebv' ]
    * Class Variable
                },
    * @param {Object} propertyValues
                variables: {
    * @returns {mw.calculators.objectClasses.Variable}
                    required: [ 'weight', 'age', 'hct', 'minHct' ]
    * @constructor
                }
    */
            },
    mw.calculators.objectClasses.Variable = function( propertyValues ) {
            digits: 0,
        var properties = {
             units: 'mL',
             required: [
            formula: '',
                'id',
            references: [
                'name',
                 'Morgan & Mikhail\'s Clinical Anesthesiology. 5e. p1168'
                 'type'
             ],
             ],
             optional: [
             calculate: function( data ) {
                 'abbreviation',
                 var currentHct = data.hct.toNumber( 'pcthct' );
                 'defaultValue',
                 var minHct = data.minHct.toNumber( 'pcthct' );
                'maxLength',
                'options',
                'units'
            ]
        };


        mw.calculators.objectClasses.CalculatorObject.call( this, properties, propertyValues );
                if( currentHct < minHct ) {
 
                    return '-';
        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;
                 return data.ebv.toNumber( 'mL' ) * ( currentHct - minHct ) / currentHct;
             }
             }
        },
        minUop: {
            name: 'Minimum urine output',
            abbreviation: 'Min UOP',
            data: {
                variables: {
                    required: [ 'weight', 'age' ],
                    optional: [ 'caseDuration' ]
                }
            },
            type: 'string',
            formula: '',
            references: [
                'Klahr S, Miller SB. Acute oliguria. N Engl J Med. 1998 Mar 5;338(10):671-5. doi: 10.1056/NEJM199803053381007. PMID: 9486997.',
                'Arant BS Jr. Postnatal development of renal function during the first year of life. Pediatr Nephrol. 1987 Jul;1(3):308-13. doi: 10.1007/BF00849229. PMID: 3153294.'
            ],
            calculate: function( data ) {
                var weight = data.weight.toNumber( 'kgwt' );
                var age = data.age.toNumber( 'yo' );
                var caseDuration = data.caseDuration ? data.caseDuration.toNumber( 'hr' ) : null;


            this.options = options;
                var minUop;
        }


        this.calculations = [];
                if( age > 1 ) {
 
                    minUop = 0.5 * weight;
        if( this.defaultValue ) {
                } else {
            this.defaultValue = this.prepareValue( this.defaultValue );
                     minUop = 1 * weight;
        }
 
        this.value = null;
    };
 
    mw.calculators.objectClasses.Variable.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
 
    mw.calculators.objectClasses.Variable.prototype.addCalculation = function( calculationId ) {
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
            return;
        }
 
        this.calculations.push( calculationId );
    };
 
    mw.calculators.objectClasses.Variable.prototype.createInput = function( inputOptions ) {
        if( !inputOptions ) {
            inputOptions = {};
        }
 
        inputOptions.class = inputOptions.hasOwnProperty( 'class' ) ? inputOptions.class : '';
        inputOptions.hideLabel = inputOptions.hasOwnProperty( 'hideLabel' ) ? inputOptions.hideLabel : false;
        inputOptions.hideLabelMobile = inputOptions.hasOwnProperty( 'hideLabelMobile' ) ? inputOptions.hideLabelMobile : false;
        inputOptions.inline = inputOptions.hasOwnProperty( 'inline' ) ? inputOptions.inline : false;
        inputOptions.inputClass = inputOptions.hasOwnProperty( 'inputClass' ) ? inputOptions.inputClass : '';
 
        var variableId = this.id;
        var inputId = 'calculator-input-' + variableId;
 
        var inputContainerTag = inputOptions.inline ? '<span>' : '<div>';
 
        var inputContainerAttributes = {
            class: 'form-group mb-0 calculator-container-input'
        };
 
        inputContainerAttributes.class += inputOptions.class ? ' ' + inputOptions.class : '';
        inputContainerAttributes.class += ' calculator-container-input-' + variableId;
 
        var inputContainerCss = {};
 
        // Initialize label attributes
        var labelAttributes = {
            for: inputId,
            html: this.getLabelString()
        };
 
        if( inputOptions.hideLabel || ( inputOptions.hideLabelMobile && mw.calculators.isMobile() ) ) {
            labelAttributes.class = 'sr-only';
        }
 
        var labelCss = {};
 
        if( inputOptions.inline ) {
            inputContainerTag = '<span>';
 
            inputContainerCss[ 'align-items' ] = 'center';
            inputContainerCss[ 'display' ] = 'flex';
            inputContainerCss[ 'height' ] = 'calc(1.5em + 0.75rem + 2px)';
 
            labelAttributes.html += ':&nbsp;';
            labelCss[ 'margin-bottom' ] = 0;
        }
 
        // Create the input container
        var $inputContainer = $( inputContainerTag, inputContainerAttributes ).css( inputContainerCss );
 
        var $label = $( '<label>', labelAttributes ).css( labelCss );
 
        $inputContainer.append( $label );
 
        var value = this.getValue();
 
        if( this.type === TYPE_NUMBER ) {
            // Initialize the primary units variables (needed for handlers, even if doesn't have units)
            var unitsId = null;
            var $unitsContainer = null;
 
            var inputValue = '';
 
            if( mw.calculators.isValueMathObject( value ) ) {
                var number = value.toNumber();
 
                if( number ) {
                     inputValue = number;
                 }
                 }
            } else {
                inputValue = value;
            }
            // Initialize input options
            var inputAttributes = {
                id: inputId,
                class: 'form-control calculator-input calculator-input-text',
                type: 'text',
                autocomplete: 'off',
                inputmode: 'decimal',
                value: inputValue
            };
            // Configure additional options
            if( this.maxLength ) {
                inputAttributes.maxlength = this.maxLength;
            }
            // Add any additional classes to the input
            inputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
            // Add the input id to the list of classes
            inputAttributes.class += ' ' + inputId;
            // If the variable has units, create the units input
            if( this.hasUnits() ) {
                // Set the units id
                unitsId = inputId + '-units';
                var unitsValue = mw.calculators.isValueMathObject( value ) ? value.formatUnits() : null;
                var unitsInputAttributes = {
                    id: unitsId
                };
                // Create the units container
                $unitsContainer = $( '<div>', {
                    class: 'input-group-append'
                } ).css( 'align-items', 'center' );
                if( this.units.length === 1 ) {
                    unitsInputAttributes.type = 'hidden';
                    unitsInputAttributes.value = this.units[ 0 ];


                    $unitsContainer
                if( caseDuration ) {
                        .css( 'padding', '0 0.5em' )
                    minUop = minUop * caseDuration + ' mL';
                        .append( mw.calculators.getUnitsString( math.unit( '0 ' + this.units[ 0 ] ) ) )
                        .append( $( '<input>', unitsInputAttributes ) );
                 } else {
                 } else {
                     // Initialize the units input options
                     minUop = minUop + ' mL/hr';
                    unitsInputAttributes.class = 'custom-select calculator-input-select';
 
                    // Add any additional classes to the input
                    unitsInputAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
 
                    unitsInputAttributes.class = unitsInputAttributes.class + ' ' + unitsId;
 
                    var $unitsInput = $( '<select>', unitsInputAttributes )
                        .on( 'change', function() {
                            var numberValue = $( '#' + inputId ).val();
 
                            var newValue = numberValue ? numberValue + ' ' + $( this ).val() : null;
 
                            mw.calculators.setValue( variableId, newValue );
                        } );
 
                    for( var iUnits in this.units ) {
                        var units = this.units[ iUnits ];
 
                        var unitsOptionAttributes = {
                            html: mw.calculators.getUnitsString( math.unit( '0 ' + units ) ),
                            value: units
                        };
 
                        if( units === unitsValue ) {
                            unitsOptionAttributes.selected = true;
                        }
 
                        $unitsInput.append( $( '<option>', unitsOptionAttributes ) );
                    }
 
                    $unitsContainer.append( $unitsInput );
                 }
                 }
            }
            // Create the input and add handlers
            var $input = $( '<input>', inputAttributes )
                .on( 'input', function() {
                    var numberValue = $( this ).val();
                    var newValue = numberValue ? numberValue : null;
                    if( newValue && unitsId ) {
                        newValue = newValue + ' ' + $( '#' + unitsId ).val();
                    }
                    mw.calculators.setValue( variableId, newValue );
                } );
            // Create the input group
            var $inputGroup = $( '<div>', {
                class: 'input-group'
            } ).append( $input );


            if( $unitsContainer ) {
                 return minUop;
                 $inputGroup.append( $unitsContainer );
             }
             }
        },
        systolicBloodPressure: {
            name: 'Systolic blood pressure',
            abbreviation: 'SBP',
            data: {
                variables: {
                    required: [ 'age' ]
                }
            },
            type: 'string',
            references: [
                'Baby Miller 6e, ch. 16, pg. 550'
            ],
            calculate: function( data ) {
                var age = data.age.toNumber( 'yo' );


            $inputContainer.append( $inputGroup );
                 var systolicMin, systolicMax, diastolicMin, diastolicMax, meanMin, meanMax;
        } else if( this.type === TYPE_STRING ) {
            if( this.hasOptions() ) {
                 var optionKeys = Object.keys( this.options );


                 if( optionKeys.length === 1 ) {
                 if( age >= 16 ) {
                     $inputContainer.append( this.options[ optionKeys[ 0 ] ] );
                    systolicMin = 100;
                    systolicMax = 125;
                } else if( age >= 13 ) {
                    systolicMin = 95;
                    systolicMax = 120;
                } else if( age >= 9 ) {
                    systolicMin = 90;
                    systolicMax = 115;
                } else if( age >= 6 ) {
                    systolicMin = 85;
                    systolicMax = 105;
                } else if( age >= 3 ) {
                    systolicMin = 80;
                    systolicMax = 100;
                } else if( age >= 1 ) {
                     systolicMin = 75;
                    systolicMax = 95;
                } else if( age >= 6 / 12 ) {
                    systolicMin = 70;
                    systolicMax = 90;
                } else if( age >= 1 / 12 ) {
                    systolicMin = 65;
                    systolicMax = 85;
                 } else {
                 } else {
                     var selectAttributes = {
                     systolicMin = 60;
                        id: inputId,
                     systolicMax = 75;
                        class: 'custom-select calculator-input calculator-input-select'
                    };
 
                    // Add any additional classes to the input
                    selectAttributes.class += inputOptions.inputClass ? ' ' + inputOptions.inputClass : '';
 
                    var $select = $( '<select>', selectAttributes )
                        .on( 'change', function() {
                            mw.calculators.setValue( variableId, $( this ).val() );
                        } );
 
                     for( var optionId in this.options ) {
                        var displayText = this.options[ optionId ];
 
                        var optionAttributes = {
                            value: optionId,
                            text: displayText
                        };
 
                        if( optionId === value ) {
                            optionAttributes.selected = true;
                        }
 
                        $select.append( $( '<option>', optionAttributes ) );
                    }
 
                    $inputContainer.append( $select );
                 }
                 }
             }
             }
         }
         }
    } );


         return $inputContainer;
    // Cardiovascular
    };
    mw.calculators.addCalculations( {
         vO2: {
            name: 'VO<sub>2</sub>',
            abbreviation: 'VO<sub>2</sub>',
            data: {
                calculations: {
                    required: [ 'bsa' ]
                },
                variables: {
                    optional: [ 'age' ]
                }
            },
            units: 'mL/min',
            references: [],
            calculate: function( data ) {
                var bsa = data.bsa.toNumber();
                var age = data.age ? data.age.toNumber( 'yr' ) : null;


    mw.calculators.objectClasses.Variable.prototype.getLabelString = function() {
                 if( age >= 70 ) {
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
                     return 110 * bsa;
    };
                 } else {
 
                     return 125 * bsa;
    mw.calculators.objectClasses.Variable.prototype.getValue = function() {
        if( this.value !== null ) {
            return this.value;
        } else if( this.defaultValue !== null ) {
            return this.defaultValue;
        } else {
            return null;
        }
    };
 
    mw.calculators.objectClasses.Variable.prototype.getValueString = function() {
        return String( this.getValue() );
    };
 
    mw.calculators.objectClasses.Variable.prototype.hasOptions = function() {
        return this.options !== null;
    };
 
    mw.calculators.objectClasses.Variable.prototype.hasUnits = function() {
        return this.units !== null;
    };
 
    mw.calculators.objectClasses.Variable.prototype.hasValue = function() {
        var value = this.getValue();
 
        if( value === null ||
            ( mw.calculators.isValueMathObject( value ) && !value.toNumber() ) ) {
            return false;
        }
 
        return true;
    };
 
    mw.calculators.objectClasses.Variable.prototype.isValueMathObject = function() {
        return mw.calculators.isValueMathObject( this.value );
    };
 
    mw.calculators.objectClasses.Variable.prototype.isValueValid = function( value ) {
        if( value === null ) {
            return true;
        }
 
        if( this.type === TYPE_NUMBER ) {
            if( typeof value !== 'object' ) {
                 value = math.unit( value );
            }
 
            if( this.hasUnits() ) {
                var valueUnits = value.formatUnits();
 
                if( !valueUnits ) {
                     throw new Error( 'Could not set value for "' + this.id + '": Value must define units' );
                 } else if( this.units.indexOf( valueUnits ) === -1 ) {
                     throw new Error( 'Could not set value for "' + this.id + '": Units "' + valueUnits + '" are not valid for this variable' );
                 }
                 }
             }
             }
         } else if( this.hasOptions() ) {
         },
             if( !this.options.hasOwnProperty( value ) ) {
        cardiacOutputFick: {
                throw new Error( 'Could not set value "' + value + '" for "' + this.id + '": Value must define be one of: ' + Object.keys( this.options ).join( ', ' ) );
             name: 'Cardiac output (Fick)',
             }
            abbreviation: 'CO (Fick)',
        }
             data: {
 
                variables: {
        return true;
                    required: [ 'saO2', 'smvO2', 'hgb' ]
    };
                },
 
                calculations: {
    mw.calculators.objectClasses.Variable.prototype.prepareValue = function( value ) {
                    required: [ 'vO2' ]
        if( !this.isValueValid( value ) ) {
            // isValueValid will throw a meaningful error to the console
            return null;
        }
 
        if( value !== null ) {
            if( this.type === TYPE_NUMBER ) {
                if( typeof value !== 'object' ) {
                    value = math.unit( value );
                 }
                 }
             }
             },
        }
            units: 'L/min',
 
            formula: '<math>\\mathrm{CO_{Fick}}=\\frac{VO_2}{(S_aO_2 - S_{mv}O_2) * H_b * 13.4}</math>',
        return value;
            link: false,
    };
            references: [],
 
            calculate: function( data ) {
    mw.calculators.objectClasses.Variable.prototype.setValue = function( value ) {
                var vO2 = data.vO2.toNumber( 'mL/min' );
        this.value = this.prepareValue( value );
                var saO2 = data.saO2.toNumber() / 100;
 
                var smvO2 = data.smvO2.toNumber() / 100;
        this.valueUpdated();
                var hgb = data.hgb.toNumber( 'ghgbperdL' );
 
        return true;
    };
 
    mw.calculators.objectClasses.Variable.prototype.valueUpdated = function() {
        for( var iCalculation in this.calculations ) {
            var calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );


            if( calculation ) {
                return vO2 / ( ( saO2 - smvO2 ) * hgb * 13.4 );
                calculation.render();
             }
             }
         }
         },
    }
         cardiacIndex: {
 
             name: 'Cardiac index',
 
             abbreviation: 'CI',
 
             data: {
    /**
                calculations: {
    * Class AbstractCalculation
                    required: [ 'bsa', 'cardiacOutputFick' ]
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.AbstractCalculation}
    * @constructor
    */
    mw.calculators.objectClasses.AbstractCalculation = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
 
         this.initialize();
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.addCalculation = function( calculationId ) {
        if( this.calculations.indexOf( calculationId ) !== -1 ) {
             return;
        }
 
        this.calculations.push( calculationId );
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.doRender = function() {};
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getContainerClass = function() {
        return 'calculator-calculation-' + this.id;
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getLabelString = function() {
        return this.id;
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties = function() {
        return {
            required: [
                'id',
                'calculate'
            ],
             optional: [
                'data',
                'description',
                'onRender',
                'onRendered',
                'references',
                'type'
            ]
        };
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getValue = function() {
        // For now, we always need to recalculate, since the calculation may not be rendered but still required by
        // other calculations (i.e. drug dosages using lean body weight).
        this.recalculate();
 
        return this.value;
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.hasInfo = function() {
        return false;
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.hasValue = function() {
        if( this.value === null ||
             ( this.isValueMathObject() && !this.value.toNumber() ) ) {
            return false;
        }
 
        return true;
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationData = function() {
        return this.data;
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.getCalculationDataValues = function() {
        var calculationData = this.getCalculationData();
 
        var data = {};
        var missingRequiredData = '';
        var calculationId, calculation, variableId, variable;
 
        for( var iRequiredCalculation in calculationData.calculations.required ) {
            calculationId = calculationData.calculations.required[ iRequiredCalculation ];
            calculation = mw.calculators.getCalculation( calculationId );
 
            if( !calculation ) {
                throw new Error( 'Invalid required calculation "' + calculationId + '" for calculation "' + this.id + '"' );
            } else if( !calculation.hasValue() ) {
                if( missingRequiredData ) {
                    missingRequiredData = missingRequiredData + ', ';
                 }
                 }
            },
            units: 'L/min/m^2',
            formula: '<math>\\mathrm{CI}=\\frac{\\mathrm{CO}}{\\mathrm{BSA}}</math>',
            link: false,
            references: [],
            calculate: function( data ) {
                var cardiacOutput = data.cardiacOutputFick.toNumber( 'L/min' );
                var bsa = data.bsa.toNumber( 'm^2' );


                 missingRequiredData = missingRequiredData + calculation.getLabelString();
                 return cardiacOutput / bsa;
            } else {
                data[ calculationId ] = calculation.value;
             }
             }
         }
         },
 
         strokeVolume: {
         for( var iRequiredVariable in calculationData.variables.required ) {
             name: 'Stroke volume',
             variableId = calculationData.variables.required[ iRequiredVariable ];
             abbreviation: 'SV',
             variable = mw.calculators.getVariable( variableId );
             data: {
 
                 variables: {
             if( !variable ) {
                    required: [ 'heartRate' ]
                 throw new Error( 'Invalid required variable "' + variableId + '" for calculation "' + this.id + '"' );
                },
            } else if( !variable.hasValue() ) {
                 calculations: {
                 if( missingRequiredData ) {
                     required: [ 'cardiacOutputFick' ]
                     missingRequiredData = missingRequiredData + ', ';
                 }
                 }
            },
            units: 'mL',
            formula: '<math>\\mathrm{SV}=\\frac{\\mathrm{CO}}{\\mathrm{HR}}</math>',
            link: false,
            references: [],
            calculate: function( data ) {
                var cardiacOutput = data.cardiacOutputFick.toNumber( 'mL/min' );
                var heartRate = data.heartRate.toNumber();


                 missingRequiredData = missingRequiredData + variable.getLabelString();
                 return cardiacOutput / heartRate;
            } else {
                data[ variableId ] = variable.getValue();
            }
        }
 
        if( missingRequiredData ) {
            this.message = missingRequiredData + ' required';
 
            return false;
        }
 
        for( var iOptionalCalculation in calculationData.calculations.optional ) {
            calculationId = calculationData.calculations.optional[ iOptionalCalculation ];
            calculation = mw.calculators.getCalculation( calculationId );
 
            if( !calculation ) {
                throw new Error( 'Invalid optional calculation "' + calculationId + '" for calculation "' + this.id + '"' );
             }
             }
            data[ calculationId ] = calculation.hasValue() ? calculation.value : null;
         }
         }
    } );


        for( var iOptionalVariable in calculationData.variables.optional ) {
     // Neuro
            variableId = calculationData.variables.optional[ iOptionalVariable ];
     mw.calculators.addCalculations( {
            variable = mw.calculators.getVariable( variableId );
         brainMass: {
 
             name: 'Brain mass',
            if( !variable ) {
             data: {
                throw new Error( 'Invalid optional variable "' + variableId + '" for calculation "' + this.id + '"' );
                 variables: {
            }
                     optional: [ 'age', 'gender' ]
 
            data[ variableId ] = variable.hasValue() ? variable.getValue() : null;
        }
 
        return data;
     };
 
     mw.calculators.objectClasses.AbstractCalculation.prototype.initialize = function() {
         if( typeof this.calculate !== 'function' ) {
             throw new Error( 'calculate() must be a function for Calculation "' + this.id + '"' );
        }
 
        // Initialize array to store calculation ids which depend on this calculation's value
        this.calculations = [];
 
        this.data = new mw.calculators.objectClasses.CalculationData( this.getCalculationData() );
 
        this.type = this.type ? this.type : TYPE_NUMBER;
 
        this.message = null;
        this.value = null;
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.isValueMathObject = function() {
        return mw.calculators.isValueMathObject( this.value );
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.recalculate = function() {
        this.message = '';
        this.value = null;
 
        var data = this.getCalculationDataValues();
 
        if( data === false ) {
            this.valueUpdated();
 
            return false;
        }
 
        try {
             var value = this.calculate( data );
 
            if( this.type === TYPE_NUMBER && !isNaN( value ) ) {
                 if( this.units ) {
                     value = value + ' ' + this.units;
                 }
                 }
            },
            digits: 0,
            units: 'gwt',
            references: [
                'Dekaban AS. Changes in brain weights during the span of human life: relation of brain weights to body heights and body weights. Ann Neurol. 1978 Oct;4(4):345-56. doi: 10.1002/ana.410040410. PMID: 727739.'
            ],
            calculate: function( data ) {
                var age = data.age ? data.age.toNumber( 'yr' ) : null;
                var gender = data.gender ? data.gender : null;


                 this.value = math.unit( value );
                 var brainMassFemale = 1290;
            } else {
                 var brainMassMale = 1450;
                 this.value = value;
            }
        } catch( e ) {
            console.warn( e.message );
 
            this.message = e.message;
            this.value = null;
        } finally {
            this.valueUpdated();
        }
 
        return true;
    };
 
 
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.render = function() {
        this.recalculate();
 
        if( typeof this.onRender === 'function' ) {
            this.onRender();
        }
 
        this.doRender();
 
        if( typeof this.onRendered === 'function' ) {
            this.onRendered();
        }
    };
 
    mw.calculators.objectClasses.AbstractCalculation.prototype.setDependencies = function() {
        this.data = this.getCalculationData();
 
        var calculationIds = this.data.calculations.required.concat( this.data.calculations.optional );


        for( var iCalculationId in calculationIds ) {
                if( age !== null ) {
            var calculationId = calculationIds[ iCalculationId ];
                    if( age <= 10 / 365 ) {
                        // <=10 days
                        brainMassFemale = 360;
                        brainMassMale = 380;
                    } else if( age <= 4 * 30 / 365 ) {
                        // Less than 4 months. This is a gap in the reported data of the paper, so linearly interpolate?
                        var ageFactor = 1 - ( 4 * 30 / 365 - age ) / ( 4 * 30 / 365 - 10 / 365 );


            if( !mw.calculators.calculations.hasOwnProperty( calculationId ) ) {
                        brainMassFemale = 360 + ageFactor * ( 580 - 360 );
                throw new Error('Calculation "' + calculationId + '" does not exist for calculation "' + this.id + '"');
                        brainMassMale = 380 + ageFactor * ( 640 - 380 );
            }
                    } else if( age <= 8 * 30 / 365 ) {
 
                        // <=8 months
            mw.calculators.calculations[ calculationId ].addCalculation( this.id );
                        brainMassFemale = 580;
        }
                        brainMassMale = 640;
 
                    } else if( age <= 18 * 30 / 365 ) {
        var variableIds = this.data.variables.required.concat( this.data.variables.optional );
                        // <=18 months
 
                        brainMassFemale = 940;
        for( var iVariableId in variableIds ) {
                        brainMassMale = 970;
            var variableId = variableIds[ iVariableId ];
                    } else if( age <= 30 * 30 / 365 ) {
 
                        // <=30 months
            if( !mw.calculators.variables.hasOwnProperty( variableId ) ) {
                        brainMassFemale = 1040;
                throw new Error('Variable "' + variableId + '" does not exist for calculation "' + this.id + '"');
                        brainMassMale = 1120;
            }
                    } else if( age <= 43 * 30 / 365 ) {
 
                        // <=43 months
            mw.calculators.variables[ variableId ].addCalculation( this.id );
                        brainMassFemale = 1090;
        }
                        brainMassMale = 1270;
 
                    } else if( age <= 5 ) {
        this.recalculate();
                        brainMassFemale = 1150;
    };
                        brainMassMale = 1300;
 
                    } else if( age <= 7 ) {
    mw.calculators.objectClasses.AbstractCalculation.prototype.valueUpdated = function() {
                        brainMassFemale = 1210;
        for( var iCalculation in this.calculations ) {
                        brainMassMale = 1330;
            calculation = mw.calculators.getCalculation( this.calculations[ iCalculation ] );
                    } else if( age <= 9 ) {
 
                        brainMassFemale = 1180;
            if( calculation ) {
                        brainMassMale = 1370;
                calculation.render();
                    } else if( age <= 12 ) {
            }
                        brainMassFemale = 1260;
        }
                        brainMassMale = 1440;
    };
                    } else if( age <= 15 ) {
 
                        brainMassFemale = 1280;
 
                        brainMassMale = 1410;
 
                    } else if( age <= 18 ) {
    /**
                        brainMassFemale = 1340;
    * Class CalculationData
                        brainMassMale = 1440;
    * @param {Object} propertyValues
                    } else if( age <= 21 ) {
    * @returns {mw.calculators.objectClasses.CalculationData}
                        brainMassFemale = 1310;
    * @constructor
                        brainMassMale = 1450;
    */
                    } else if( age <= 30 ) {
    mw.calculators.objectClasses.CalculationData = function( propertyValues ) {
                        brainMassFemale = 1300;
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
                        brainMassMale = 1440;
 
                    } else if( age <= 40 ) {
        var dataTypes = this.getDataTypes();
                        brainMassFemale = 1290;
        var dataRequirements = this.getDataRequirements();
                        brainMassMale = 1440;
 
                    } else if( age <= 50 ) {
        // Iterate through the supported data types (e.g. calculation, variable) to initialize the structure
                        brainMassFemale = 1290;
        for( var iDataType in dataTypes ) {
                        brainMassMale = 1430;
            var dataType = dataTypes[ iDataType ];
                    } else if( age <= 55 ) {
 
                        brainMassFemale = 1280;
            if( !this[ dataType ] ) {
                        brainMassMale = 1410;
                this[ dataType ] = {
                    } else if( age <= 60 ) {
                    optional: [],
                        brainMassFemale = 1250;
                     required: []
                        brainMassMale = 1370;
                };
                    } else if( age <= 65 ) {
            } else {
                        brainMassFemale = 1240;
                // Iterate through the requirement levels (i.e. optional, required) to initialize the structure
                        brainMassMale = 1370;
                for( var iDataRequirement in dataRequirements ) {
                    } else if( age <= 70 ) {
                    var dataRequirement = dataRequirements[ iDataRequirement ];
                        brainMassFemale = 1240;
 
                        brainMassMale = 1360;
                     if( this[ dataType ].hasOwnProperty( dataRequirement ) ) {
                     } else if( age <= 75 ) {
                         for( var iDataId in this[ dataType ][ dataRequirement ] ) {
                        brainMassFemale = 1230;
                            var dataId = this[ dataType ][ dataRequirement ][ iDataId ];
                        brainMassMale = 1350;
                         }
                     } else if( age <= 80 ) {
                         brainMassFemale = 1190;
                        brainMassMale = 1330;
                    } else if( age <= 85 ) {
                        brainMassFemale = 1170;
                         brainMassMale = 1310;
                     } else {
                     } else {
                         this[ dataType ][ dataRequirement ] = [];
                         brainMassFemale = 1140;
                        brainMassMale = 1290;
                     }
                     }
                 }
                 }
            }
        }
    };


    mw.calculators.objectClasses.CalculationData.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
                if( gender === 'F' ) {
 
                    return brainMassFemale;
    mw.calculators.objectClasses.CalculationData.prototype.getDataRequirements = function() {
                 } else if( gender === 'M' ) {
        return [
                    return brainMassMale;
            'optional',
                 } else {
            'required'
                     return ( brainMassFemale + brainMassMale ) / 2;
        ];
                 }
    };
 
    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 );
             }
             }
         }
         },
 
         cerebralBloodVolume: {
         return mergedData;
            name: 'Cerebral blood volume',
    };
            abbreviation: 'CBV',
 
            data: {
 
                calculations: {
 
                    required: [ 'brainMass' ]
 
                }
 
            },
    /**
            units: 'mL',
    * Class SimpleCalculation
            description: '4 mL per 100g of brain mass',
    * @param {Object} propertyValues
            references: [
    * @returns {mw.calculators.objectClasses.SimpleCalculation}
                'Tameem A, Krovvidi H, Cerebral physiology, Continuing Education in Anaesthesia Critical Care & Pain, Volume 13, Issue 4, August 2013, Pages 113–118, https://doi.org/10.1093/bjaceaccp/mkt001'
    * @constructor
            ],
    */
            calculate: function( data ) {
    mw.calculators.objectClasses.SimpleCalculation = function( propertyValues ) {
                var brainMass = data.brainMass.toNumber( 'gwt' );
        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 ) {
                 return 4 * brainMass / 100;
                 href = mw.util.getUrl( matches[ 1 ] );
             }
             }
 
        },
             labelHtml = $( '<a>', {
        cerebralBloodFlow: {
                 href: href,
            name: 'Cerebral blood flow',
                 text: labelHtml
             abbreviation: 'CBF',
            } )[ 0 ].outerHTML;
            data: {
        }
                 calculations: {
 
                    required: [ 'brainMass' ]
        return labelHtml;
                },
    };
                 variables: {
 
                    optional: [ 'paCO2' ]
    mw.calculators.objectClasses.SimpleCalculation.prototype.getLabelString = function() {
                }
        return mw.calculators.isMobile() && this.abbreviation ? this.abbreviation : this.name;
            },
    };
            units: 'mL/min',
 
            description: '50 mL/min per 100g of brain mass. Every mmHg in PaCO2 changes CBF by 1.5 mL/min per 100g of brain mass.',
    mw.calculators.objectClasses.SimpleCalculation.prototype.getProperties = function() {
            references: [
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculation.prototype.getProperties();
                'Tameem A, Krovvidi H, Cerebral physiology, Continuing Education in Anaesthesia Critical Care & Pain, Volume 13, Issue 4, August 2013, Pages 113–118, https://doi.org/10.1093/bjaceaccp/mkt001',
 
                'Brian JE Jr. Carbon dioxide and the cerebral circulation. Anesthesiology. 1998 May;88(5):1365-86. doi: 10.1097/00000542-199805000-00029. PMID: 9605698.'
        return this.mergeProperties( inheritedProperties, {
            required: [
                'name'
             ],
             ],
             optional: [
             calculate: function( data ) {
                'abbreviation',
                var brainMass = data.brainMass.toNumber( 'gwt' );
                'digits',
                var paCO2 = data.paCO2.toNumber( 'mmHg' );
                'formula',
                'link',
                'units'
            ]
        } );
    };
 
    mw.calculators.objectClasses.SimpleCalculation.prototype.getValueString = function() {
        if( this.message ) {
            return this.message;
        } else if( typeof this.value === 'object' && this.value.hasOwnProperty( 'value' ) ) {
            return mw.calculators.getValueString( this.value );
        } else {
            return String( this.value );
        }
    };
 
    mw.calculators.objectClasses.SimpleCalculation.prototype.doRender = function() {
        var $calculationContainer = $( '.' + this.getContainerClass() );
 
        if( !$calculationContainer.length ) {
            return;
        }
 
        var valueString = this.getValueString();
 
        var inputVariableIds = this.data.variables.required.concat( this.data.variables.optional );
        var missingVariableInputs = [];
 
        for( var iInputVariableId in inputVariableIds ) {
            var variableId = inputVariableIds[ iInputVariableId ];
 
            if( !$( '#calculator-input-' + variableId ).length ) {
                missingVariableInputs.push( variableId );
            }
        }
 
        var calculation = this;
 
        $calculationContainer.each( function() {
            $( this ).empty();
 
            var isTable = this.tagName.toLowerCase() === 'tr';


            var $infoButton = null;
                var cerebralBloodFlow = 50 * brainMass / 100;


            if( calculation.hasInfo() ) {
                if( paCO2 ) {
                $infoButton = $( '<a>', {
                     // CO2 reductions don't reduce CBF more than 50%
                     'data-toggle': 'collapse',
                     var minCerebralBloodFlow = cerebralBloodFlow / 2;
                     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();
                    cerebralBloodFlow += 1.5 * brainMass / 100 * ( paCO2 - 40 );


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


                 $( this )
                 return cerebralBloodFlow;
                    .append( $( '<th>', {
                        class: 'calculator-SimpleCalculator-calculation-cell',
                        html: labelHtml
                    } ) )
                    .append( $( '<td>', {
                        class: 'calculator-SimpleCalculator-value-cell',
                        html: valueString
                    } ) );
            } else {
                $( this )
                    .append( labelHtml + $infoButton[ 0 ].outerHTML + ': ' + valueString );
             }
             }
 
        },
            if( calculation.hasInfo() ) {
        cerebralMetabolicRateO2: {
                var infoHtml = '';
            name: 'Cerebral metabolic rate (O<sub>2</sub>)',
 
            abbreviation: 'CMRO<sub>2</sub>',
                if( calculation.description ) {
            data: {
                    infoHtml += $( '<p>', {
                calculations: {
                        html: calculation.description
                     required: [ 'brainMass' ]
                    } )[ 0 ].outerHTML;
                 },
                }
                 variables: {
 
                     optional: [ 'temperature' ]
                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();
                 }
                 }
            },
            units: 'mL/min',
            description: '3 mL O<sub>2</sub>/min per 100g of brain mass',
            references: [
                'Tameem A, Krovvidi H, Cerebral physiology, Continuing Education in Anaesthesia Critical Care & Pain, Volume 13, Issue 4, August 2013, Pages 113–118, https://doi.org/10.1093/bjaceaccp/mkt001'
            ],
            calculate: function( data ) {
                var brainMass = data.brainMass.toNumber( 'gwt' );


                 if( isTable ) {
                 return 3 * brainMass / 100;
                    $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 ) {
        cerebralMetabolicRateGlucose: {
                var variablesContainerClass = 'calculator-SimpleCalculator-variables ' + calculation.getContainerClass() + '-variables';
            name: 'Cerebral metabolic rate (Glucose)',
                var inputGroup = mw.calculators.createInputGroup( missingVariableInputs );
            abbreviation: 'CMR<sub>glu</sub>',
 
            data: {
                if( isTable ) {
                calculations: {
                    $variablesContainer =  $( '<tr>' )
                     required: [ 'brainMass' ]
                        .append( $( '<td>', {
                            class: variablesContainerClass,
                            colspan: 2
                        } ).append( inputGroup ) );
                } else {
                     $variablesContainer = $( '<div>', {
                        class: variablesContainerClass
                    } ).append( inputGroup );
                 }
                 }
            },
            units: 'mg/min',
            description: '5 mg glucose/min per 100g of brain mass',
            references: [
                'Tameem A, Krovvidi H, Cerebral physiology, Continuing Education in Anaesthesia Critical Care & Pain, Volume 13, Issue 4, August 2013, Pages 113–118, https://doi.org/10.1093/bjaceaccp/mkt001'
            ],
            calculate: function( data ) {
                var brainMass = data.brainMass.toNumber( 'gwt' );


                 $( this ).after( $variablesContainer );
                 return 5 * brainMass / 100;
 
                missingVariableInputs = [];
             }
             }
         } );
         }
     };
     } );


    var tableMaxWidth = 600;


 
    mw.calculators.addCalculators( moduleId, {
 
        anatomy: {
 
            name: 'Patient statistics',
    /**
            calculations: [
    * Class AbstractCalculator
                'bmi',
    * @param {Object} propertyValues
                'bsa',
    * @returns {mw.calculators.objectClasses.AbstractCalculator}
                'ibw',
    * @constructor
                'lbw'
    */
            ],
    mw.calculators.objectClasses.AbstractCalculator = function( propertyValues ) {
            css: {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
                'max-width': tableMaxWidth
    };
            },
 
            table: true
    mw.calculators.objectClasses.AbstractCalculator.prototype = Object.create( mw.calculators.objectClasses.CalculatorObject.prototype );
        },
 
        fluidManagement: {
    mw.calculators.objectClasses.AbstractCalculator.prototype.getCalculatorClass = function() {
            name: 'Fluid management',
        return '';
            calculations: [
    };
                'fluidMaintenanceRate',
 
                'intraopFluids',
    mw.calculators.objectClasses.AbstractCalculator.prototype.getContainerClass = function() {
                'ebv',
        return 'calculator-' + this.module + '-' + this.id;
                'maxAbl',
    };
                'minUop'
 
            ],
    mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties = function() {
            css: {
         return {
                'max-width': tableMaxWidth
             required: [
            },
                 'id',
            table: true
                 'module',
        },
                 'name',
        cardiovascular: {
                 'calculations'
            name: 'Cardiovascular',
            calculations: [
                'vO2',
                'cardiacOutputFick',
                'cardiacIndex',
                'strokeVolume'
            ],
            css: {
                'max-width': tableMaxWidth
            },
            table: true
        },
         neuro: {
             name: 'Neuro',
            calculations: [
                 'brainMass',
                 'cerebralBloodVolume',
                 'cerebralBloodFlow',
                'cerebralMetabolicRateO2',
                 'cerebralMetabolicRateGlucose'
             ],
             ],
             optional: [
             css: {
                 'onRender',
                 'max-width': tableMaxWidth
                'onRendered'
             },
             ]
             table: true
        };
    };
 
    mw.calculators.objectClasses.AbstractCalculator.prototype.render = function() {
        if( typeof this.onRender === 'function' ) {
             this.onRender();
        }
 
        this.doRender();
 
        if( typeof this.onRendered === 'function' ) {
            this.onRendered();
         }
         }
     };
     } );
 
 
    mw.calculators.objectClasses.AbstractCalculator.prototype.doRender = function() {};
 
 
 
 
 
    /**
    * Class SimpleCalculator
    * @param {Object} propertyValues
    * @returns {mw.calculators.objectClasses.SimpleCalculator}
    * @constructor
    */
    mw.calculators.objectClasses.SimpleCalculator = function( propertyValues ) {
        mw.calculators.objectClasses.CalculatorObject.call( this, this.getProperties(), propertyValues );
    };
 
    mw.calculators.objectClasses.SimpleCalculator.prototype = Object.create( mw.calculators.objectClasses.AbstractCalculator.prototype );
 
    mw.calculators.objectClasses.SimpleCalculator.prototype.doRender = function() {
        var $calculatorContainer = $( '.' + this.getContainerClass() );
 
        if( !$calculatorContainer.length ) {
            return;
        }
 
        $calculatorContainer.addClass( this.getCalculatorClass() );
 
        if( this.css ) {
            $calculatorContainer.css( this.css );
        }
 
        $calculatorContainer.empty();
 
        $calculatorContainer.append( $( '<h4>', {
            text: this.name
        } ) );
 
        var $calculationsContainer;
 
        if( this.table ) {
            $calculationsContainer = $( '<table>', {
                class: 'wikitable'
            } ).append( '<tbody>' );
 
            $calculationsContainer
                .append( $( '<tr>' )
                    .append(
                        $( '<th>', {
                            class: this.getCalculatorClass() + '-calculation-header'
                        } ).text( 'Calculation' ),
                        $( '<th>', {
                            class: this.getCalculatorClass() + '-value-header'
                        }  ).text( 'Value' )
                    )
                );
        } else {
            $calculationsContainer = $( '<div>' );
        }
 
        $calculatorContainer.append( $calculationsContainer );
 
        for( var iCalculationId in this.calculations ) {
            var calculation = mw.calculators.getCalculation( this.calculations[ iCalculationId ] );
            var calculationContainerClass = calculation.getContainerClass();
 
            var $calculationContainer = $( '.' + calculationContainerClass );
 
            // If a container doesn't exist yet, add it
            if( !$calculationContainer.length ) {
                if( this.table ) {
                    $calculationContainer = $( '<tr>', {
                        class: calculationContainerClass
                    } );
                } else {
                    $calculationContainer = $( '<div>', {
                        class: calculationContainerClass
                    } );
                }
 
                $calculationsContainer.append( $calculationContainer );
            }
 
            calculation.render();
        }
    };
 
    mw.calculators.objectClasses.SimpleCalculator.prototype.getCalculatorClass = function() {
        return 'calculator-SimpleCalculator';
    };
 
 
    mw.calculators.objectClasses.SimpleCalculator.prototype.getProperties = function() {
        var inheritedProperties = mw.calculators.objectClasses.AbstractCalculator.prototype.getProperties();
 
        return this.mergeProperties( inheritedProperties, {
            required: [],
            optional: [
                'css',
                'table'
            ]
        } );
    };
 
    mw.calculators.initialize();
 
}() );
}() );

Revision as of 03:40, 21 August 2021

( function() {
    var moduleId = 'anatomyPhysiology';

    mw.calculators.addUnitsBases( {
        bpm: {
            toString: function( units ) {
                units = units.replace( 'bpm', 'beats/min' );

                return units;
            }
        },
        hgb: {
            toString: function( units ) {
                units = units.replace( 'hgbperdL', '/dL' );
                units = units.replace( 'pcthct', '%' );

                return units;
            }
        },
        o2: {
            toString: function( units ) {
                units = units.replace( 'pcto2', '%' );

                return units;
            }
        },
        temperature: {
            toString: function( units ) {
                units = units.replace( 'deg', '&deg;' );

                return units;
            }
        }
    } );

    mw.calculators.addUnits( {
        bpm: {
            basename: 'bpm'
        },
        pcthct: {
            baseName: 'hgb'
        },
        pcto2: {
            baseName: 'o2'
        },
        ghgbperdL: {
            baseName: 'hgb',
            prefixes: 'short',
            definition: '3 pcthct'
        }
    } );

    mw.calculators.addVariables( {
        caseDuration: {
            name: 'Case duration',
            type: 'number',
            abbreviation: 'Duration',
            maxLength: 3,
            units: [
                'hr',
                'min'
            ]
        },
        hct: {
            name: 'Current hematocrit',
            type: 'number',
            abbreviation: 'Current hct',
            defaultValue: '45 pcthct',
            maxLength: 4,
            units: [
                'pcthct',
                'ghgbperdL'
            ]
        },
        heartRate: {
            name: 'Heart rate',
            type: 'number',
            abbreviation: 'HR',
            defaultValue: '60 bpm',
            maxLength: 4,
            units: [
                'bpm'
            ]
        },
        hgb: {
            name: 'Hemoglobin',
            type: 'number',
            abbreviation: 'HgB',
            defaultValue: '13 ghgbperdL',
            maxLength: 4,
            units: [
                'pcthct',
                'ghgbperdL'
            ]
        },
        minHct: {
            name: 'Minimum hematocrit',
            type: 'number',
            abbreviation: 'Min hct',
            defaultValue: '21 pcthct',
            maxLength: 4,
            units: [
                'pcthct',
                'ghgbperdL'
            ]
        },
        paCO2: {
            name: 'PaCO<sub>2</sub>',
            type: 'number',
            abbreviation: 'PaCO<sub>2</sub>',
            defaultValue: '40 mmHg',
            maxLength: 3,
            units: [
                'mmHg'
            ]
        },
        saO2: {
            name: 'SaO<sub>2</sub>',
            type: 'number',
            abbreviation: 'SaO<sub>2</sub>',
            defaultValue: '100 pcto2',
            maxLength: 3,
            units: [
                'pcto2'
            ]
        },
        smvO2: {
            name: 'SmvO<sub>2</sub>',
            type: 'number',
            abbreviation: 'SmvO<sub>2</sub>',
            defaultValue: '75 pcto2',
            maxLength: 3,
            units: [
                'pcto2'
            ]
        },
        npoTime: {
            name: 'Time spent NPO',
            type: 'number',
            abbreviation: 'NPO time',
            defaultValue: '8 hr',
            maxLength: 2,
            units: [
                'hr'
            ]
        },
        surgicalTrauma: {
            name: 'Severity of surgical trauma',
            type: 'string',
            abbreviation: 'Surgical trauma',
            defaultValue: 'Minimal',
            options: [
                'Minimal',
                'Moderate',
                'Severe'
            ]
        },
        temperature: {
            name: 'Temperature',
            type: 'number',
            abbreviation: 'Temp',
            defaultValue: '37 degC',
            maxLength: 5,
            units: [
                'degC',
                'degF'
            ]
        }
    } );



    mw.calculators.addCalculations( {
        bmi: {
            name: 'Body mass index',
            abbreviation: 'BMI',
            data: {
                variables: {
                    required: [ 'weight', 'height' ]
                }
            },
            digits: 0,
            units: 'kg/m^2',
            formula: '<math>\\mathrm{BMI} = \\frac{\\mathrm{mass_{kg}}}{{\\mathrm{height_{m}}}^2}</math>',
            link: '[[Body mass index]]',
            references: [],
            calculate: function( data ) {
                return data.weight.toNumber( 'kgwt' ) / Math.pow( data.height.toNumber( 'm' ), 2 );
            }
        },
        bsa: {
            name: 'Body surface area',
            abbreviation: 'BSA',
            data: {
                variables: {
                    required: [ 'weight', 'height' ]
                }
            },
            digits: 2,
            units: 'm^2',
            formula: '<math>\\mathrm{BSA} = \\sqrt{\\frac{\\mathrm{weight_{kg}}*\\mathrm{height_{cm}}}{3600}}</math>',
            link: false,
            references: [
                'Mosteller RD. Simplified calculation of body-surface area. N Engl J Med. 1987 Oct 22;317(17):1098. doi: 10.1056/NEJM198710223171717. PMID: 3657876.'
            ],
            calculate: function( data ) {
                return Math.sqrt( data.height.toNumber( 'cm' ) * data.weight.toNumber( 'kgwt' ) / 3600 );
            }
        },
        ebv: {
            name: 'Estimated blood volume',
            abbreviation: 'EBV',
            data: {
                variables: {
                    required: [ 'weight', 'age' ]
                }
            },
            digits: 0,
            units: 'mL',
            formula: '',
            references: [
                'Morgan & Mikhail\'s Clinical Anesthesiology. 5e. p1168'
            ],
            calculate: function( data ) {
                var weight = data.weight.toNumber( 'kgwt' );
                var age = data.age.toNumber( 'yo' );

                var ebvPerKg;

                if( age >= 1 ) {
                    if( data.gender === 'F' ) {
                        ebvPerKg = 65;
                    } else {
                        ebvPerKg = 75;
                    }
                } else if( age >= 1/12 ) {
                    ebvPerKg = 80;
                } else if( age >= 0 ) {
                    ebvPerKg = 85;
                } else {
                    ebvPerKg = 95;
                }

                return weight * ebvPerKg;
            }
        },
        fluidMaintenanceRate: {
            name: 'Fluid maintenance rate',
            abbreviation: 'Fluid maint.',
            data: {
                variables: {
                    required: [ 'weight' ]
                }
            },
            digits: 0,
            units: 'mL/hr',
            formula: '',
            references: [
                'Miller\'s Anesthesia 7e, section IV, pg. 1728'
            ],
            calculate: function( data ) {
                var weight = data.weight.toNumber( 'kgwt' );

                // Uses 4-2-1 rule
                var maintenanceRate = 4 * Math.min( weight, 10 );

                if( weight > 10 ) {
                    maintenanceRate += 2 * Math.min( weight - 10, 10 );
                }

                if( weight > 20) {
                    maintenanceRate += weight - 20;
                }

                return maintenanceRate;
            }
        },
        intraopFluids: {
            name: 'Intraoperative fluid dosing',
            abbreviation: 'Intraop fluids',
            data: {
                calculations: {
                    required: [ 'fluidMaintenanceRate' ]
                },
                variables: {
                    required: [ 'weight', 'npoTime', 'surgicalTrauma' ]
                }
            },
            type: 'string',
            references: [
                'Corcoran T, Rhodes JE, Clarke S, Myles PS, Ho KM. Perioperative fluid management strategies in major surgery: a stratified meta-analysis. Anesth Analg. 2012 Mar;114(3):640-51. doi: 10.1213/ANE.0b013e318240d6eb. Epub 2012 Jan 16. PMID: 22253274.'
            ],
            calculate: function( data ) {
                var weight = data.weight.toNumber( 'kgwt' );
                var maintenanceRate = data.fluidMaintenanceRate.toNumber( 'mL/hr' );
                var npoTime = data.npoTime.toNumber( 'hr' );
                var surgicalTrauma = data.surgicalTrauma;

                var output = '';

                var npoDeficit = npoTime * maintenanceRate;

                var surgicalLossMin, surgicalLossMax;

                if( surgicalTrauma === 'Minimal' ) {
                    surgicalLossMin = 2 * weight;
                    surgicalLossMax = 4 * weight;
                } else if( surgicalTrauma === 'Moderate' ) {
                    surgicalLossMin = 4 * weight;
                    surgicalLossMax = 6 * weight;
                } else {
                    surgicalLossMin = 6 * weight;
                    surgicalLossMax = 8 * weight;
                }

                var firstHour = Math.round( npoDeficit / 2 ) + maintenanceRate;
                var nextHoursMin = Math.round( npoDeficit / 4 ) + maintenanceRate + surgicalLossMin;
                var nextHoursMax = Math.round( npoDeficit / 4 ) + maintenanceRate + surgicalLossMax;
                var remainingHoursMin = maintenanceRate + surgicalLossMin;
                var remainingHoursMax = maintenanceRate + surgicalLossMax;

                output += 'NPO deficit: ' + Math.round( npoDeficit ) + ' mL<br/>';
                output += 'Surgical losses: ' + surgicalLossMin + '-' + surgicalLossMax + ' mL/hr<br/>';
                output += '1st hour: ' + firstHour + ' mL<br/>';
                output += '2nd hour: ' + nextHoursMin + '-' + nextHoursMax + ' mL<br/>';
                output += '3rd hour: ' + nextHoursMin + '-' + nextHoursMax + ' mL<br/>';
                output += '4+ hours: ' + remainingHoursMin + '-' + remainingHoursMax + ' mL<br/>';

                return output;
            }
        },
        maxAbl: {
            name: 'Maximum allowable blood loss',
            abbreviation: 'Max ABL',
            data: {
                calculations: {
                    required: [ 'ebv' ]
                },
                variables: {
                    required: [ 'weight', 'age', 'hct', 'minHct' ]
                }
            },
            digits: 0,
            units: 'mL',
            formula: '',
            references: [
                'Morgan & Mikhail\'s Clinical Anesthesiology. 5e. p1168'
            ],
            calculate: function( data ) {
                var currentHct = data.hct.toNumber( 'pcthct' );
                var minHct = data.minHct.toNumber( 'pcthct' );

                if( currentHct < minHct ) {
                    return '-';
                }

                return data.ebv.toNumber( 'mL' ) * ( currentHct - minHct ) / currentHct;
            }
        },
        minUop: {
            name: 'Minimum urine output',
            abbreviation: 'Min UOP',
            data: {
                variables: {
                    required: [ 'weight', 'age' ],
                    optional: [ 'caseDuration' ]
                }
            },
            type: 'string',
            formula: '',
            references: [
                'Klahr S, Miller SB. Acute oliguria. N Engl J Med. 1998 Mar 5;338(10):671-5. doi: 10.1056/NEJM199803053381007. PMID: 9486997.',
                'Arant BS Jr. Postnatal development of renal function during the first year of life. Pediatr Nephrol. 1987 Jul;1(3):308-13. doi: 10.1007/BF00849229. PMID: 3153294.'
            ],
            calculate: function( data ) {
                var weight = data.weight.toNumber( 'kgwt' );
                var age = data.age.toNumber( 'yo' );
                var caseDuration = data.caseDuration ? data.caseDuration.toNumber( 'hr' ) : null;

                var minUop;

                if( age > 1 ) {
                    minUop = 0.5 * weight;
                } else {
                    minUop = 1 * weight;
                }

                if( caseDuration ) {
                    minUop = minUop * caseDuration + ' mL';
                } else {
                    minUop = minUop + ' mL/hr';
                }

                return minUop;
            }
        },
        systolicBloodPressure: {
            name: 'Systolic blood pressure',
            abbreviation: 'SBP',
            data: {
                variables: {
                    required: [ 'age' ]
                }
            },
            type: 'string',
            references: [
                'Baby Miller 6e, ch. 16, pg. 550'
            ],
            calculate: function( data ) {
                var age = data.age.toNumber( 'yo' );

                var systolicMin, systolicMax, diastolicMin, diastolicMax, meanMin, meanMax;

                if( age >= 16 ) {
                    systolicMin = 100;
                    systolicMax = 125;
                } else if( age >= 13 ) {
                    systolicMin = 95;
                    systolicMax = 120;
                } else if( age >= 9 ) {
                    systolicMin = 90;
                    systolicMax = 115;
                } else if( age >= 6 ) {
                    systolicMin = 85;
                    systolicMax = 105;
                } else if( age >= 3 ) {
                    systolicMin = 80;
                    systolicMax = 100;
                } else if( age >= 1 ) {
                    systolicMin = 75;
                    systolicMax = 95;
                } else if( age >= 6 / 12 ) {
                    systolicMin = 70;
                    systolicMax = 90;
                } else if( age >= 1 / 12 ) {
                    systolicMin = 65;
                    systolicMax = 85;
                } else {
                    systolicMin = 60;
                    systolicMax = 75;
                }
            }
        }
    } );

    // Cardiovascular
    mw.calculators.addCalculations( {
        vO2: {
            name: 'VO<sub>2</sub>',
            abbreviation: 'VO<sub>2</sub>',
            data: {
                calculations: {
                    required: [ 'bsa' ]
                },
                variables: {
                    optional: [ 'age' ]
                }
            },
            units: 'mL/min',
            references: [],
            calculate: function( data ) {
                var bsa = data.bsa.toNumber();
                var age = data.age ? data.age.toNumber( 'yr' ) : null;

                if( age >= 70 ) {
                    return 110 * bsa;
                } else {
                    return 125 * bsa;
                }
            }
        },
        cardiacOutputFick: {
            name: 'Cardiac output (Fick)',
            abbreviation: 'CO (Fick)',
            data: {
                variables: {
                    required: [ 'saO2', 'smvO2', 'hgb' ]
                },
                calculations: {
                    required: [ 'vO2' ]
                }
            },
            units: 'L/min',
            formula: '<math>\\mathrm{CO_{Fick}}=\\frac{VO_2}{(S_aO_2 - S_{mv}O_2) * H_b * 13.4}</math>',
            link: false,
            references: [],
            calculate: function( data ) {
                var vO2 = data.vO2.toNumber( 'mL/min' );
                var saO2 = data.saO2.toNumber() / 100;
                var smvO2 = data.smvO2.toNumber() / 100;
                var hgb = data.hgb.toNumber( 'ghgbperdL' );

                return vO2 / ( ( saO2 - smvO2 ) * hgb * 13.4 );
            }
        },
        cardiacIndex: {
            name: 'Cardiac index',
            abbreviation: 'CI',
            data: {
                calculations: {
                    required: [ 'bsa', 'cardiacOutputFick' ]
                }
            },
            units: 'L/min/m^2',
            formula: '<math>\\mathrm{CI}=\\frac{\\mathrm{CO}}{\\mathrm{BSA}}</math>',
            link: false,
            references: [],
            calculate: function( data ) {
                var cardiacOutput = data.cardiacOutputFick.toNumber( 'L/min' );
                var bsa = data.bsa.toNumber( 'm^2' );

                return cardiacOutput / bsa;
            }
        },
        strokeVolume: {
            name: 'Stroke volume',
            abbreviation: 'SV',
            data: {
                variables: {
                    required: [ 'heartRate' ]
                },
                calculations: {
                    required: [ 'cardiacOutputFick' ]
                }
            },
            units: 'mL',
            formula: '<math>\\mathrm{SV}=\\frac{\\mathrm{CO}}{\\mathrm{HR}}</math>',
            link: false,
            references: [],
            calculate: function( data ) {
                var cardiacOutput = data.cardiacOutputFick.toNumber( 'mL/min' );
                var heartRate = data.heartRate.toNumber();

                return cardiacOutput / heartRate;
            }
        }
    } );

    // Neuro
    mw.calculators.addCalculations( {
        brainMass: {
            name: 'Brain mass',
            data: {
                variables: {
                    optional: [ 'age', 'gender' ]
                }
            },
            digits: 0,
            units: 'gwt',
            references: [
                'Dekaban AS. Changes in brain weights during the span of human life: relation of brain weights to body heights and body weights. Ann Neurol. 1978 Oct;4(4):345-56. doi: 10.1002/ana.410040410. PMID: 727739.'
            ],
            calculate: function( data ) {
                var age = data.age ? data.age.toNumber( 'yr' ) : null;
                var gender = data.gender ? data.gender : null;

                var brainMassFemale = 1290;
                var brainMassMale = 1450;

                if( age !== null ) {
                    if( age <= 10 / 365 ) {
                        // <=10 days
                        brainMassFemale = 360;
                        brainMassMale = 380;
                    } else if( age <= 4 * 30 / 365 ) {
                        // Less than 4 months. This is a gap in the reported data of the paper, so linearly interpolate?
                        var ageFactor = 1 - ( 4 * 30 / 365 - age ) / ( 4 * 30 / 365 - 10 / 365 );

                        brainMassFemale = 360 + ageFactor * ( 580 - 360 );
                        brainMassMale = 380 + ageFactor * ( 640 - 380 );
                    } else if( age <= 8 * 30 / 365 ) {
                        // <=8 months
                        brainMassFemale = 580;
                        brainMassMale = 640;
                    } else if( age <= 18 * 30 / 365 ) {
                        // <=18 months
                        brainMassFemale = 940;
                        brainMassMale = 970;
                    } else if( age <= 30 * 30 / 365 ) {
                        // <=30 months
                        brainMassFemale = 1040;
                        brainMassMale = 1120;
                    } else if( age <= 43 * 30 / 365 ) {
                        // <=43 months
                        brainMassFemale = 1090;
                        brainMassMale = 1270;
                    } else if( age <= 5 ) {
                        brainMassFemale = 1150;
                        brainMassMale = 1300;
                    } else if( age <= 7 ) {
                        brainMassFemale = 1210;
                        brainMassMale = 1330;
                    } else if( age <= 9 ) {
                        brainMassFemale = 1180;
                        brainMassMale = 1370;
                    } else if( age <= 12 ) {
                        brainMassFemale = 1260;
                        brainMassMale = 1440;
                    } else if( age <= 15 ) {
                        brainMassFemale = 1280;
                        brainMassMale = 1410;
                    } else if( age <= 18 ) {
                        brainMassFemale = 1340;
                        brainMassMale = 1440;
                    } else if( age <= 21 ) {
                        brainMassFemale = 1310;
                        brainMassMale = 1450;
                    } else if( age <= 30 ) {
                        brainMassFemale = 1300;
                        brainMassMale = 1440;
                    } else if( age <= 40 ) {
                        brainMassFemale = 1290;
                        brainMassMale = 1440;
                    } else if( age <= 50 ) {
                        brainMassFemale = 1290;
                        brainMassMale = 1430;
                    } else if( age <= 55 ) {
                        brainMassFemale = 1280;
                        brainMassMale = 1410;
                    } else if( age <= 60 ) {
                        brainMassFemale = 1250;
                        brainMassMale = 1370;
                    } else if( age <= 65 ) {
                        brainMassFemale = 1240;
                        brainMassMale = 1370;
                    } else if( age <= 70 ) {
                        brainMassFemale = 1240;
                        brainMassMale = 1360;
                    } else if( age <= 75 ) {
                        brainMassFemale = 1230;
                        brainMassMale = 1350;
                    } else if( age <= 80 ) {
                        brainMassFemale = 1190;
                        brainMassMale = 1330;
                    } else if( age <= 85 ) {
                        brainMassFemale = 1170;
                        brainMassMale = 1310;
                    } else {
                        brainMassFemale = 1140;
                        brainMassMale = 1290;
                    }
                }

                if( gender === 'F' ) {
                    return brainMassFemale;
                } else if( gender === 'M' ) {
                    return brainMassMale;
                } else {
                    return ( brainMassFemale + brainMassMale ) / 2;
                }
            }
        },
        cerebralBloodVolume: {
            name: 'Cerebral blood volume',
            abbreviation: 'CBV',
            data: {
                calculations: {
                    required: [ 'brainMass' ]
                }
            },
            units: 'mL',
            description: '4 mL per 100g of brain mass',
            references: [
                'Tameem A, Krovvidi H, Cerebral physiology, Continuing Education in Anaesthesia Critical Care & Pain, Volume 13, Issue 4, August 2013, Pages 113–118, https://doi.org/10.1093/bjaceaccp/mkt001'
            ],
            calculate: function( data ) {
                var brainMass = data.brainMass.toNumber( 'gwt' );

                return 4 * brainMass / 100;
            }
        },
        cerebralBloodFlow: {
            name: 'Cerebral blood flow',
            abbreviation: 'CBF',
            data: {
                calculations: {
                    required: [ 'brainMass' ]
                },
                variables: {
                    optional: [ 'paCO2' ]
                }
            },
            units: 'mL/min',
            description: '50 mL/min per 100g of brain mass. Every mmHg in PaCO2 changes CBF by 1.5 mL/min per 100g of brain mass.',
            references: [
                'Tameem A, Krovvidi H, Cerebral physiology, Continuing Education in Anaesthesia Critical Care & Pain, Volume 13, Issue 4, August 2013, Pages 113–118, https://doi.org/10.1093/bjaceaccp/mkt001',
                'Brian JE Jr. Carbon dioxide and the cerebral circulation. Anesthesiology. 1998 May;88(5):1365-86. doi: 10.1097/00000542-199805000-00029. PMID: 9605698.'
            ],
            calculate: function( data ) {
                var brainMass = data.brainMass.toNumber( 'gwt' );
                var paCO2 = data.paCO2.toNumber( 'mmHg' );

                var cerebralBloodFlow = 50 * brainMass / 100;

                if( paCO2 ) {
                    // CO2 reductions don't reduce CBF more than 50%
                    var minCerebralBloodFlow = cerebralBloodFlow / 2;

                    cerebralBloodFlow += 1.5 * brainMass / 100 * ( paCO2 - 40 );

                    cerebralBloodFlow = math.max( cerebralBloodFlow, minCerebralBloodFlow );
                }

                return cerebralBloodFlow;
            }
        },
        cerebralMetabolicRateO2: {
            name: 'Cerebral metabolic rate (O<sub>2</sub>)',
            abbreviation: 'CMRO<sub>2</sub>',
            data: {
                calculations: {
                    required: [ 'brainMass' ]
                },
                variables: {
                    optional: [ 'temperature' ]
                }
            },
            units: 'mL/min',
            description: '3 mL O<sub>2</sub>/min per 100g of brain mass',
            references: [
                'Tameem A, Krovvidi H, Cerebral physiology, Continuing Education in Anaesthesia Critical Care & Pain, Volume 13, Issue 4, August 2013, Pages 113–118, https://doi.org/10.1093/bjaceaccp/mkt001'
            ],
            calculate: function( data ) {
                var brainMass = data.brainMass.toNumber( 'gwt' );

                return 3 * brainMass / 100;
            }
        },
        cerebralMetabolicRateGlucose: {
            name: 'Cerebral metabolic rate (Glucose)',
            abbreviation: 'CMR<sub>glu</sub>',
            data: {
                calculations: {
                    required: [ 'brainMass' ]
                }
            },
            units: 'mg/min',
            description: '5 mg glucose/min per 100g of brain mass',
            references: [
                'Tameem A, Krovvidi H, Cerebral physiology, Continuing Education in Anaesthesia Critical Care & Pain, Volume 13, Issue 4, August 2013, Pages 113–118, https://doi.org/10.1093/bjaceaccp/mkt001'
            ],
            calculate: function( data ) {
                var brainMass = data.brainMass.toNumber( 'gwt' );

                return 5 * brainMass / 100;
            }
        }
    } );

    var tableMaxWidth = 600;

    mw.calculators.addCalculators( moduleId, {
        anatomy: {
            name: 'Patient statistics',
            calculations: [
                'bmi',
                'bsa',
                'ibw',
                'lbw'
            ],
            css: {
                'max-width': tableMaxWidth
            },
            table: true
        },
        fluidManagement: {
            name: 'Fluid management',
            calculations: [
                'fluidMaintenanceRate',
                'intraopFluids',
                'ebv',
                'maxAbl',
                'minUop'
            ],
            css: {
                'max-width': tableMaxWidth
            },
            table: true
        },
        cardiovascular: {
            name: 'Cardiovascular',
            calculations: [
                'vO2',
                'cardiacOutputFick',
                'cardiacIndex',
                'strokeVolume'
            ],
            css: {
                'max-width': tableMaxWidth
            },
            table: true
        },
        neuro: {
            name: 'Neuro',
            calculations: [
                'brainMass',
                'cerebralBloodVolume',
                'cerebralBloodFlow',
                'cerebralMetabolicRateO2',
                'cerebralMetabolicRateGlucose'
            ],
            css: {
                'max-width': tableMaxWidth
            },
            table: true
        }
    } );
}() );