"use strict";

/* --- called initially at start of app --- */
function DisableSideMenu() {
    // console.log("DisableSideMenu called");
    try {
        UserMgmtEnabledFlag = false;
        var sidebarButtons = document.querySelectorAll('.sidebar-button');
        sidebarButtons.forEach(function(button) {
            button.classList.add('disabled');
            button.style.pointerEvents = 'none';
        });

        var btnTime = document.querySelector('#btnTime');
        if (btnTime) {
            btnTime.classList.add('disabled');
            btnTime.style.pointerEvents = 'none';
        } else {
            // console.warn("btnTime not found");
        }

        var btnPreop = document.querySelector('#btnPreop');
        if (btnPreop) {
            btnPreop.classList.add('disabled');
            btnPreop.style.pointerEvents = 'none';
        } else {
            // console.warn("btnPreop not found");
        }

        var btnCaseHelp = document.querySelector('#btnCaseHelp');
        if (btnCaseHelp) {
            btnCaseHelp.classList.add('disabled');
            btnCaseHelp.style.pointerEvents = 'none';
        } else {
            // console.warn("btnCaseHelp not found");
        }

        var btnCaseLog = document.querySelector('#btnCaseLog');
        if (btnCaseLog) {
            btnCaseLog.classList.add('disabled');
            btnCaseLog.style.pointerEvents = 'none';
        } else {
            // console.warn("btnCaseLog not found");
        }

        var btnNewCase = document.querySelector('#btnNewCase');
        if (btnNewCase) {
            btnNewCase.classList.add('disabled');
            btnNewCase.style.pointerEvents = 'none';
        } else {
            // console.warn("btnNewCase not found");
        }

    } catch (error) {
        // console.error("Error in DisableSideMenu:", error);
    }
}

function EnableSideMenu() {
    try {
        UserMgmtEnabledFlag = true;
        var sidebarButtons = document.querySelectorAll('.sidebar-button');
        sidebarButtons.forEach(function(button) {
            button.classList.remove('disabled');
            button.style.pointerEvents = 'auto';
            // console.log(button.querySelector('span').textContent + " enabled");
        });

        var btnTime = document.querySelector('#btnTime');
        if (btnTime) {
            btnTime.classList.remove('disabled');
            btnTime.style.pointerEvents = 'auto';
        } else {
            // console.warn("btnTime not found");
        }

        var btnPreop = document.querySelector('#btnPreop');
        if (btnPreop) {
            btnPreop.classList.remove('disabled');
            btnPreop.style.pointerEvents = 'auto';
        } else {
            // console.warn("btnPreop not found");
        }

        var btnCaseHelp = document.querySelector('#btnCaseHelp');
        if (btnCaseHelp) {
            if (CurrentCase && CurrentCase.helpFlag) {
				btnCaseHelp.classList.remove('disabled');
				btnCaseHelp.style.pointerEvents = 'auto';
            } else {
				btnCaseHelp.classList.add('disabled');
				btnCaseHelp.style.pointerEvents = 'none';
            }
        } else {
           //  // console.warn("btnCaseHelp not found");
        }

        var btnCaseLog = document.querySelector('#btnCaseLog');
        if (btnCaseLog) {
            btnCaseLog.classList.remove('disabled');
            btnCaseLog.style.pointerEvents = 'auto';
        } else {
            // console.warn("btnCaseLog not found");
        }

        var btnNewCase = document.querySelector('#btnNewCase');
        if (btnNewCase) {
            btnNewCase.classList.remove('disabled');
            btnNewCase.style.pointerEvents = 'auto';
        } else {
            // console.warn("btnNewCase not found");
        }

    } catch (error) {
        // console.error("Error in EnableSideMenu:", error);
    }
}

function EnableSecondTopBarButtons() {
    try {
        var btnCaseHelp = document.querySelector('#btnCaseHelp');
        if (btnCaseHelp) {
            if (CurrentCase && CurrentCase.helpFlag) {
				btnCaseHelp.classList.remove('disabled');
				btnCaseHelp.style.pointerEvents = 'auto';
            } else {
				btnCaseHelp.classList.add('disabled');
				btnCaseHelp.style.pointerEvents = 'none';
            }
        } else {
           // console.warn("btnCaseHelp not found");
        }

        var btnCaseLog = document.querySelector('#btnCaseLog');
        if (btnCaseLog) {
            btnCaseLog.classList.remove('disabled');
            btnCaseLog.style.pointerEvents = 'auto';
        } else {
            // console.warn("btnCaseLog not found");
        }

        var btnNewCase = document.querySelector('#btnNewCase');
        if (btnNewCase) {
            btnNewCase.classList.remove('disabled');
            btnNewCase.style.pointerEvents = 'auto';
        } else {
            // console.warn("btnNewCase not found");
        }

    } catch (error) {
        // console.error("Error in EnableSecondTopBarButtons:", error);
    }
}


function SetupButtonListeners() {
    // console.log("SetupButtonListeners called");
    try {
        // Setup sidebar buttons
        var sidebarButtons = document.querySelectorAll('.sidebar-button');
        sidebarButtons.forEach(function(button) {
            var action = button.className.split(' ')[1].split('-')[1];
            button.onclick = function(event) {
                event.preventDefault();
                return handleSidebarClick(action);
            };
            // console.log("Listener set for sidebar button: " + action);
        });

        // Setup other buttons
        var buttonActions = {
            "btnTime": ClickBtnTime,
            "btnCaseHelp": ShowCaseHelpScreen,
            "btnPreop": ShowPreopScreen,
            "btnPatient": ShowPatientScreen,
            "btnMonitors": ShowMonitorsScreen,
            "btnAirway": ShowAirwayScreen,
            "btnBreathing": ShowBreathingScreen,
            "btnDrugs": ShowDrugsScreen,
            "btnFluids": ShowFluidsScreen,
            "btnLabs": ShowLabsScreen,
            "btnSurgeon": ShowSurgeonScreen,
            "btnResuscitate": ShowResuscitateScreen,
            "btnCaseLog": ShowCaseLogScreen,
            "btnNewCase": ClickBtnNewCase,
            "btnGo": GoNbp
        };

        for (var buttonId in buttonActions) {
            var button = document.getElementById(buttonId);
            if (button) {
                button.onclick = buttonActions[buttonId];
                // console.log("Listener set for button: " + buttonId);
            } else {
                // console.warn("Button not found: " + buttonId);
            }
        }

        // console.log("Button listeners setup complete");
    } catch (error) {
        // console.error("Error in SetupButtonListeners:", error);
    }
}

function GoNbp() {
    NbpTimer = UserNbpInterval * 60 - 1;
    UserNbpModeStr = "inflating";
    NbpM = 0
}

function RefreshBobbin() {
    var tmpTop;
    PrpTotalFlow = UserO2Flow + UserAirFlow + UserN2OFlow;


    if (PrpTotalFlow < 1) {
        tmpTop = 88 - 14 * PrpTotalFlow /* was 90-20 */
    } else if (PrpTotalFlow < 2) {
        tmpTop = 74 - 16 * (PrpTotalFlow - 1)
    } else if (PrpTotalFlow < 5) {
        tmpTop = 58 - 6 * (PrpTotalFlow - 2)
    } else if (PrpTotalFlow < 10) {
        tmpTop = 41 - 3 * (PrpTotalFlow - 5)
    } else if (PrpTotalFlow < 20) {
        tmpTop = 25 - 1.5 * (PrpTotalFlow - 10)
    } else if (PrpTotalFlow < 25) {
        tmpTop = 10 - (PrpTotalFlow - 20)
    } else {
        tmpTop = 5
    }
	
    document.getElementById("bobbin").style.top = tmpTop + "%";
}

function ClickBtnTime() {
    window.UserShowingWhatNowFlag = false;
    
    if (typeof window.CaseLogStr2 === 'undefined') {
        window.CaseLogStr2 = "";
    }
	
    var displayContent = document.getElementById("divDisplayContent");
    if (displayContent) {
        displayContent.innerHTML = "";
        
        var myDiv = document.createElement("div");
        myDiv.id = "divPause";
        
        var myP = document.createElement("p");
        myP.id = "pPause";
        myP.innerHTML = "The simulation was suspended.";
        myDiv.appendChild(myP);
        
        myDiv.appendChild(document.createElement("br"));
        
        var myButton = document.createElement("button");
        myButton.id = "btnResume";
        myButton.innerHTML = "Resume";
        myButton.classList.remove('disabled');
        myButton.style.pointerEvents = 'auto';
        myButton.onclick = ClickBtnResume; // Modern event listener
        myDiv.appendChild(myButton);
        
        displayContent.appendChild(myDiv);
    }

    var caseLog = document.getElementById("divCaseLog2");
    if (caseLog) {
        caseLog.style.display = 'none';
    }

    const elementsToDisable = [
        "seldivN2O", "seldivAir", "seldivO2", 
        "selVaporizer", "selVapAmount", "btnGo"
    ];

    elementsToDisable.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.classList.add('disabled');
            element.style.pointerEvents = 'none';
        }
    });

    window.CaseLogStr2 += "The simulation was suspended.\n";

    if (typeof window.MyTimeout !== 'undefined') {
        clearTimeout(window.MyTimeout);
    }

    if (typeof DisableSideMenu === 'function') {
        DisableSideMenu();
    }
}

function ClickBtnResume() {
    window.UserShowingCenter = "caselog"; // Set default view
    ShowCaseLogScreen(); // restore the view content
    
    if (typeof EnableSideMenu === 'function') {
        EnableSideMenu();
    }

    const elementsToEnable = [
        "seldivN2O", "seldivAir", "seldivO2", 
        "selVaporizer", "selVapAmount", "btnGo"
    ];

    elementsToEnable.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.classList.remove('disabled');
            element.style.pointerEvents = 'auto';
        }
    });

    if (typeof Update === 'function' && typeof TimeoutInterval !== 'undefined') {
        window.MyTimeout = setTimeout(Update, TimeoutInterval);
    }
}

function CreateDropListFlow(inputBox) {
    var selectlist = document.createElement("select");
    selectlist.setAttribute("id", "sel" + inputBox.id);
    inputBox.appendChild(selectlist);
    var tmpFlow;
    for (var i = 0; i <= 28; i++) {
        var option = document.createElement("option");
        if (i < 10) {
            tmpFlow = i * 0.1
        } else {
            tmpFlow = (i - 10) * 0.5 + 1.0
        }
        option.innerHTML = tmpFlow.toFixed(1);
        option.setAttribute("value", tmpFlow);
        $("sel" + inputBox.id).appendChild(option)
    }
    var label = document.createElement("span");
    if (inputBox.id == "divN2O") {
        label.innerHTML = "L/min N2O"
    } else if (inputBox.id == "divAir") {
        label.innerHTML = "L/min Air"
    } else {
        label.innerHTML = "L/min O2"
    }
    $("" + inputBox.id).appendChild(label)
}

function CreateDropListVapAmount(inputBox) {
    var selectlist = document.createElement("select");
    selectlist.setAttribute("id", "selVapAmount");
    inputBox.appendChild(selectlist);
    SetVaporizerValues()
}

function SetAirFlow() {
    UserAirFlow = parseFloat($("seldivAir").value)
	RecordAirFlow();
}

function SetN2OFlow() {
    UserN2OFlow = parseFloat($("seldivN2O").value)
	RecordN2OFlow();
}

function SetO2Flow() {
    UserO2Flow = parseFloat($("seldivO2").value)
	RecordO2Flow();
}

function ChangeVaporizer() {
    UserVaporizerStr = $("selVaporizer").value;
//was    $("divVaporizer").style.backgroundImage = "url(" + "'app/images/" + UserVaporizerStr + ".jpg')";
    $("divVaporizer").style.backgroundImage = "url(app/images/" + UserVaporizerStr + ".jpg)";
    SetVaporizerValues()
}

function SetVapAmount() {
    UserVaporizerAmount = parseFloat($("selVapAmount").value);
	if ((UserShowingCenter == "drugs") && (DrugInfo.Drugs[UserDrugIndex].nameStr == UserVaporizerStr)) {
		$("selDrugInfusion").value = UserVaporizerAmount;
		$("pDrugConfirmation").hide();
	}
    if (UserVaporizerAmount == 0) {
		$("selVaporizer").classList.remove('disabled');
		$("selVaporizer").style.pointerEvents = 'auto';
    } else {
		$("selVaporizer").classList.add('disabled');
		$("selVaporizer").style.pointerEvents = 'none';
    }
	RecordVapFlow();
}

function SetVaporizerValues() {
    $("selVapAmount").innerHTML = "";
    switch (UserVaporizerStr) {
        case "Desflurane":
            for (var i = 0; i <= DSF.length - 1; i++) {
                var option = document.createElement("option");
                option.innerHTML = DSF[i].toFixed(1);
                option.setAttribute("value", DSF[i]);
                $("selVapAmount").appendChild(option)
            }
            break;
        case "Halothane":
            for (var i = 0; i <= HAL.length - 1; i++) {
                var option = document.createElement("option");
                option.innerHTML = HAL[i].toFixed(1);
                option.setAttribute("value", HAL[i]);
                $("selVapAmount").appendChild(option)
            }
            break;
        case "Isoflurane":
            for (var i = 0; i <= ISF.length - 1; i++) {
                var option = document.createElement("option");
                option.innerHTML = ISF[i].toFixed(1);
                option.setAttribute("value", ISF[i]);
                $("selVapAmount").appendChild(option)
            }
            break;
        case "Sevoflurane":
            for (var i = 0; i <= SEV.length - 1; i++) {
                var option = document.createElement("option");
                option.innerHTML = SEV[i].toFixed(1);
                option.setAttribute("value", SEV[i]);
                $("selVapAmount").appendChild(option)
            }
            break;
        default:
            throw "invalid UserVaporizerStr" + UserVaporizerStr;
    }
/* -----------------------------------------------
	if (UserShowingCenter == "drugs") {
		$("selDrugInfusion").value = UserVaporizerAmount;
		$("pDrugConfirmation").hide();
	}
-------------------------------------------------- */
}

function ShowCaseHelpScreen() {
	UserShowingCenter = "casehelp"; 
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnWhatNow");
    myButton.innerHTML = "What Now?";
            myButton.classList.add('disabled');
            myButton.style.pointerEvents = 'none';
    $("divDisplayContent").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnLearningObj");
    myButton.innerHTML = "Objectives";
            myButton.classList.remove('disabled');
            myButton.style.pointerEvents = 'auto';
    $("divDisplayContent").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnAbout");
    myButton.innerHTML = "About";
            myButton.classList.remove('disabled');
            myButton.style.pointerEvents = 'auto';
    $("divDisplayContent").appendChild(myButton);
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divInfo");
    $("divDisplayContent").appendChild(myDiv);
    $("btnWhatNow").observe("click", ShowWhatNow);
    $("btnLearningObj").observe("click", ShowLearningObj);
    $("btnAbout").observe("click", ShowAbout);
    ShowWhatNow()
}

function ShowWhatNow() {
    UserShowingWhatNowFlag = true;
            $("btnWhatNow").classList.add('disabled');
            $("btnWhatNow").style.pointerEvents = 'none';
            $("btnLearningObj").classList.remove('disabled');
            $("btnLearningObj").style.pointerEvents = 'auto';
            $("btnAbout").classList.remove('disabled');
            $("btnAbout").style.pointerEvents = 'auto';
    $("divInfo").innerHTML = "";
    var myP = document.createElement("p");
    myP.setAttribute("id", "pWhatNow");
    myP.classList.add("divInfo");
    if (UserOverdosedFlag == false) {
        myP.innerHTML = "What Now:<br /><br />" + CurrentState.whatNextMsg
    } else {
        myP.innerHTML = "What Now:<br /><br />You administered an excessively large dose of " + DrugInfo.Drugs[UserDrugIndex].nameStr + ".<br />End of simulation. You should do this case again.\n"
    }
    $("divInfo").appendChild(myP)
}

function ShowLearningObj() {
    UserShowingWhatNowFlag = false;
            $("btnWhatNow").classList.remove('disabled');
            $("btnWhatNow").style.pointerEvents = 'auto';
            $("btnLearningObj").classList.add('disabled');
            $("btnLearningObj").style.pointerEvents = 'none';
            $("btnAbout").classList.remove('disabled');
            $("btnAbout").style.pointerEvents = 'auto';
    $("divInfo").innerHTML = "";
    var wrapperDiv = document.createElement("div");
    wrapperDiv.setAttribute("id", "learningObjWrapper");
    $("divInfo").appendChild(wrapperDiv);
    var scrollDiv = document.createElement("div");
    scrollDiv.setAttribute("id", "learningObjScroller");
    $("learningObjWrapper").appendChild(scrollDiv);
    var preTxt = document.createElement("pre");
    preTxt.innerHTML = CurrentCase.learningObj;
    $("learningObjScroller").appendChild(preTxt);  
    CreateScroller("learningObjScroller"); 
}

function ShowAbout() {
    UserShowingWhatNowFlag = false;
            $("btnWhatNow").classList.remove('disabled');
            $("btnWhatNow").style.pointerEvents = 'auto';
            $("btnLearningObj").classList.remove('disabled');
            $("btnLearningObj").style.pointerEvents = 'auto';
            $("btnAbout").classList.add('disabled');
            $("btnAbout").style.pointerEvents = 'none';
    $("divInfo").innerHTML = "";
    var wrapperDiv = document.createElement("div");
    wrapperDiv.setAttribute("id", "aboutWrapper");
    $("divInfo").appendChild(wrapperDiv);
    var scrollDiv = document.createElement("div");
    scrollDiv.setAttribute("id", "aboutScroller");
    $("aboutWrapper").appendChild(scrollDiv);
    var preTxt = document.createElement("pre");
    preTxt.innerHTML = AboutAnesthSim6.aboutinfo;
    $("aboutScroller").appendChild(preTxt);
    CreateScroller("aboutScroller")   
}



function ShowPreopScreen() {
	UserShowingCenter = "preop"; 
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
    var divWrapper = document.createElement("div");
    divWrapper.setAttribute("id", "divPreopWrapper");
    $("divDisplayContent").appendChild(divWrapper);
    var divScroll = document.createElement("div");
    divScroll.setAttribute("id", "preopScroller");
    $("divPreopWrapper").appendChild(divScroll);
    var preTxt = document.createElement("pre");
    preTxt.innerHTML = CurrentCase.preopMsg;
    $("preopScroller").appendChild(preTxt);   
    CreateScroller("preopScroller");          
}

function ShowPatientScreen() {
	UserShowingCenter = "patient"; 
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
	
    var divPat1 = document.createElement("div");
    divPat1.setAttribute("id", "divPatient1");
    $("divDisplayContent").appendChild(divPat1);
    var myP = document.createElement("p");
    myP.innerHTML = "At Time: " + MakeTimeStr() + " :";
    myP.setAttribute("id", "pTime");
    divPat1.appendChild(myP);
    var myList = document.createElement("ul");
    divPat1.appendChild(myList);
    var myBullet = document.createElement("li");
    myBullet.innerHTML = CurrentState.mentalStatusMsg;
    myList.appendChild(myBullet);
    var myBullet = document.createElement("li");
    myBullet.innerHTML = CurrentState.pupilsMsg;
    myList.appendChild(myBullet);
    var myBullet = document.createElement("li");
    myBullet.innerHTML = CurrentState.lidReflexMsg;
    myList.appendChild(myBullet);
    var myBullet = document.createElement("li");
    var myBs;
    if ((PrpTubeStatusStr == "tubeInEsophagus") && (PrpMonTv * PrpMonRr > 8.0 * CurrentCase.leanBodyMass)) {
        myBs = "The breath sounds are louder over the stomach than the lungs."
    } else if ((PrpTubeStatusStr == "tubeInRightMainstem") && (PrpMonTv * PrpMonRr > 8.0 * CurrentCase.leanBodyMass)) {
        myBs = "The breath sounds are louder on the right than the left."
    } else if (PrpTubeStatusStr == "tubeAboveCords") {
        myBs = "There are noisy glottic sounds."
    } else if ((PrpAlvTv < 1.0 * CurrentCase.leanBodyMass) || (PrpAlvRr < 2)) {
        myBs = "The breath sounds are absent."
    } else if ((PrpAlvTv < 5.0 * CurrentCase.leanBodyMass) || (PrpAlvRr < 6)) {
        myBs = "The breath sounds are reduced."
    } else {
        myBs = CurrentState.breathSoundsMsg
    }
    myBullet.innerHTML = "" + myBs;
    myList.appendChild(myBullet);
    var myBullet = document.createElement("li");
    myBullet.innerHTML = CurrentState.heartSoundsMsg;
    myList.appendChild(myBullet);
    var myBullet = document.createElement("li");
    myBullet.innerHTML = CurrentState.pulseMsg;
    myList.appendChild(myBullet);
    var myBullet = document.createElement("li");
    myBullet.innerHTML = CurrentState.skinMsg;
    myList.appendChild(myBullet);
	
    var divPat2 = document.createElement("div");
    divPat2.setAttribute("id", "divPatient2");
    $("divDisplayContent").appendChild(divPat2);
    var myP = document.createElement("p");
    myP.innerHTML = "Patient Position";
    myP.setAttribute("id", "pPosition");
    divPat2.appendChild(myP);
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selPosition");
    var myOption = document.createElement("option");
    myOption.innerHTML = "Supine";
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "Trendelenberg";
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "Reverse Trendelenberg";
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "Sitting";
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "Left Uterine Displacement";
    mySelect.appendChild(myOption);
    divPat2.appendChild(mySelect);
	
    var divPat3 = document.createElement("div");
    divPat3.setAttribute("id", "divPatient3");
    $("divDisplayContent").appendChild(divPat3);
	
    var myP = document.createElement("p");
    myP.innerHTML = "Control Temperature";
    myP.setAttribute("id", "pTemp");
    divPat3.appendChild(myP);
	
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbIcedIv");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbIcedIv";
    myLabel.appendChild(document.createTextNode("Iced IV"));
    divPat3.appendChild(myCheckbox);
    divPat3.appendChild(myLabel);
	
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbWarmIv");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbWarmIv";
    myLabel.appendChild(document.createTextNode("Warm IV"));
    divPat3.appendChild(myCheckbox);
    divPat3.appendChild(myLabel);

    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbIcePack");
    myCheckbox.id = "cbIcePack";
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbIcePack";
    myLabel.appendChild(document.createTextNode("Ice Pack"));
    divPat3.appendChild(myCheckbox);
    divPat3.appendChild(myLabel);
	
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbWarmBlanket");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbWarmBlanket";
    myLabel.appendChild(document.createTextNode("Warm Blanket"));
    divPat3.appendChild(myCheckbox);
    divPat3.appendChild(myLabel);
	
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbIcedLavage");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbIcedLavage";
    myLabel.appendChild(document.createTextNode("Iced Lavage"));
    divPat3.appendChild(myCheckbox);
    divPat3.appendChild(myLabel);
	
	
    if (UserPositionStr == "supine") {
        $("selPosition").options[0].selected = true
    } else if (UserPositionStr == "trend") {
        $("selPosition").options[1].selected = true
    } else if (UserPositionStr == "reverseTrend") {
        $("selPosition").options[2].selected = true
    } else if (UserPositionStr == "sitting") {
        $("selPosition").options[3].selected = true
    } else if (UserPositionStr == "leftUterine") {
        $("selPosition").options[4].selected = true
    }
    if (UserDoingWarmIvFlag == true) {
        $("cbWarmIv").checked = true
    } else {
        $("cbWarmIv").checked = false
    }
    if (UserDoingWarmBlanketFlag == true) {
        $("cbWarmBlanket").checked = true
    } else {
        $("cbWarmBlanket").checked = false
    }
    if (UserDoingIcedIvFlag == true) {
        $("cbIcedIv").checked = true
    } else {
        $("cbIcedIv").checked = false
    }
    if (UserDoingIcePackFlag == true) {
        $("cbIcePack").checked = true
    } else {
        $("cbIcePack").checked = false
    }
    if (UserDoingIcedLavageFlag == true) {
        $("cbIcedLavage").checked = true
    } else {
        $("cbIcedLavage").checked = false
    }
    $("selPosition").observe("change", ChangePosition);
    $("cbWarmIv").observe("click", ClickWarmIv);
    $("cbWarmBlanket").observe("click", ClickWarmBlanket);
    $("cbIcedIv").observe("click", ClickIcedIv);
    $("cbIcePack").observe("click", ClickIcePack);
    $("cbIcedLavage").observe("click", ClickIcedLavage);
    CaseLogStr2 = CaseLogStr2.concat("Assessed the patient.\n")
}

function ChangePosition() {
    if ($("selPosition").value == "Supine") {
        UserPositionStr = "supine";
        CaseLogStr2 = CaseLogStr2.concat("Position changed to supine.\n")
    } else if ($("selPosition").value == "Trendelenberg") {
        UserPositionStr = "trend";
        CaseLogStr2 = CaseLogStr2.concat("Position changed to trendelenberg.\n")
    } else if ($("selPosition").value == "Reverse Trendelenberg") {
        UserPositionStr = "reverseTrend";
        CaseLogStr2 = CaseLogStr2.concat("Position changed to reverse trendelenberg.\n")
    } else if ($("selPosition").value == "Sitting") {
        UserPositionStr = "sitting";
        CaseLogStr2 = CaseLogStr2.concat("Position changed to sitting.\n")
    } else if ($("selPosition").value == "Left Uterine Displacement") {
        UserPositionStr = "leftUterine";
        CaseLogStr2 = CaseLogStr2.concat("Position changed to left uterine displacement.\n")
    }
}

function ClickWarmIv() {
    if ($("cbWarmIv").checked == true) {
        UserDoingWarmIvFlag = true;
        CaseLogStr2 = CaseLogStr2.concat("IV fluid warmer placed.\n")
    } else {
        UserDoingWarmIvFlag = false;
        CaseLogStr2 = CaseLogStr2.concat("IV fluid warmer removed.\n")
    }
}

function ClickWarmBlanket() {
    if ($("cbWarmBlanket").checked == true) {
        UserDoingWarmBlanketFlag = true;
        CaseLogStr2 = CaseLogStr2.concat("Warm blanket in place.\n")
    } else {
        UserDoingWarmBlanketFlag = false;
        CaseLogStr2 = CaseLogStr2.concat("Warm blanket removed.\n")
    }
}

function ClickIcedIv() {
    if ($("cbIcedIv").checked == true) {
        UserDoingIcedIvFlag = true;
        CaseLogStr2 = CaseLogStr2.concat("IV fluid iced.\n")
    } else {
        UserDoingIcedIvFlag = false;
        CaseLogStr2 = CaseLogStr2.concat("Iced IV fluid removed.\n")
    }
}

function ClickIcePack() {
    if ($("cbIcePack").checked == true) {
        UserDoingIcePackFlag = true;
        CaseLogStr2 = CaseLogStr2.concat("Ice pack in place.\n")
    } else {
        UserDoingIcePackFlag = false;
        CaseLogStr2 = CaseLogStr2.concat("Ice pack removed.\n")
    }
}

function ClickIcedLavage() {
    if ($("cbIcedLavage").checked == true) {
        UserDoingIcedLavageFlag = true;
        CaseLogStr2 = CaseLogStr2.concat("Iced lavage started.\n")
    } else {
        UserDoingIcedLavageFlag = false;
        CaseLogStr2 = CaseLogStr2.concat("Iced lavage stopped.\n")
    }
}

function ShowMonitorsScreen() {
	UserShowingCenter = "monitors"; 
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divMonitors1");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pCatheters");
    myP.innerHTML = "Invasive Catheters";
    myDiv.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnInsertArtLine");
    myButton.innerHTML = "Insert Art-Line";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnInsertCvp");
    myButton.innerHTML = "Insert CVP";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnInsertPaCath");
    myButton.innerHTML = "Insert PA Catheter";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnInsertFoley");
    myButton.innerHTML = "Insert Foley";
    myDiv.appendChild(myButton);
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divMonitors2");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pMonDisplay");
    myP.innerHTML = "Monitor Display";
    myDiv.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnMeasureNbp");
    myButton.innerHTML = "Measure NBP";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnDisplayAbp");
    myButton.innerHTML = "Display ABP";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnDisplayCvp");
    myButton.innerHTML = "Display CVP";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnDisplayPap");
    myButton.innerHTML = "Display PAP";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnDisplayPawp");
    myButton.innerHTML = "Display PAWP";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnMeasureCo");
    myButton.innerHTML = "Cardiac Output";
    myDiv.appendChild(myButton);
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divMonitors3");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pNerveStim");
    myP.innerHTML = "Nerve Stimulator";
    myDiv.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnToF");
    myButton.innerHTML = "Train of Four";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnTetanus");
    myButton.innerHTML = "Tetanus";
    myDiv.appendChild(myButton);
    var linebreak = document.createElement("br");
    myDiv.appendChild(linebreak);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pNerveStimResults");
    myP.innerHTML = "";
    myDiv.appendChild(myP);
    $("btnInsertArtLine").observe("click", InsertArtLine);
    $("btnInsertCvp").observe("click", InsertCvp);
    $("btnInsertPaCath").observe("click", InsertPaCath);
    $("btnInsertFoley").observe("click", InsertFoley);
    $("btnMeasureNbp").observe("click", DisplayNbp);
    $("btnDisplayAbp").observe("click", DisplayAbp);
    $("btnDisplayCvp").observe("click", DisplayCvp);
    $("btnDisplayPap").observe("click", DisplayPap);
    $("btnDisplayPawp").observe("click", DisplayPawp);
    $("btnMeasureCo").observe("click", MeasureCo);
    $("btnToF").observe("click", DisplayToF);
    $("btnTetanus").observe("click", DisplayTetanus);
    SetMonitorButtons()
}

function SetMonitorButtons() {
    if (UserInsertedArtLineFlag) {
            $("btnInsertArtLine").classList.add('disabled');
            $("btnInsertArtLine").style.pointerEvents = 'none';
    } else {
            $("btnInsertArtLine").classList.remove('disabled');
            $("btnInsertArtLine").style.pointerEvents = 'auto';
    }
    if ((UserInsertedArtLineFlag) && (UserMonitorDisplayStr != "abp")) {
            $("btnDisplayAbp").classList.remove('disabled');
            $("btnDisplayAbp").style.pointerEvents = 'auto';
    } else {
            $("btnDisplayAbp").classList.add('disabled');
            $("btnDisplayAbp").style.pointerEvents = 'none';
    }
    if (UserInsertedCvpFlag) {
            $("btnInsertCvp").classList.add('disabled');
            $("btnInsertCvp").style.pointerEvents = 'none';
    } else {
            $("btnInsertCvp").classList.remove('disabled');
            $("btnInsertCvp").style.pointerEvents = 'auto';
    }
    if ((UserInsertedCvpFlag) && (UserMonitorDisplayStr != "cvp")) {
            $("btnDisplayCvp").classList.remove('disabled');
            $("btnDisplayCvp").style.pointerEvents = 'auto';
    } else {
            $("btnDisplayCvp").classList.add('disabled');
            $("btnDisplayCvp").style.pointerEvents = 'none';
    }
    if (UserInsertedPaCathFlag) {
            $("btnInsertPaCath").classList.add('disabled');
            $("btnInsertPaCath").style.pointerEvents = 'none';
            $("btnMeasureCo").classList.remove('disabled');
            $("btnMeasureCo").style.pointerEvents = 'auto';
    } else {
            $("btnInsertPaCath").classList.remove('disabled');
            $("btnInsertPaCath").style.pointerEvents = 'auto';
            $("btnMeasureCo").classList.add('disabled');
            $("btnMeasureCo").style.pointerEvents = 'none';
    }
    if ((UserInsertedPaCathFlag) && (UserMonitorDisplayStr != "pap")) {
            $("btnDisplayPap").classList.remove('disabled');
            $("btnDisplayPap").style.pointerEvents = 'auto';
    } else {
            $("btnDisplayPap").classList.add('disabled');
            $("btnDisplayPap").style.pointerEvents = 'none';
    }
    if ((UserInsertedPaCathFlag) && (UserMonitorDisplayStr != "pawp")) {
            $("btnDisplayPawp").classList.remove('disabled');
            $("btnDisplayPawp").style.pointerEvents = 'auto';
    } else {
            $("btnDisplayPawp").classList.add('disabled');
            $("btnDisplayPawp").style.pointerEvents = 'none';
   }
    if (UserInsertedFoleyFlag) {
            $("btnInsertFoley").classList.add('disabled');
            $("btnInsertFoley").style.pointerEvents = 'none';
    } else {
            $("btnInsertFoley").classList.remove('disabled');
            $("btnInsertFoley").style.pointerEvents = 'auto';
    }
}

function InsertArtLine() {
    UserInsertedArtLineFlag = true;
    UserMonitorDisplayStr = "abp";
    SetMonitorButtons();
    CaseLogStr2 = CaseLogStr2.concat("Arterial line inserted.\n")
}

function InsertCvp() {
    UserInsertedCvpFlag = true;
    UserMonitorDisplayStr = "cvp";
    SetMonitorButtons();
    CaseLogStr2 = CaseLogStr2.concat("Central venous line inserted.\n")
}

function InsertFoley() {
    UserInsertedFoleyFlag = true;
    SetMonitorButtons();
    CaseLogStr2 = CaseLogStr2.concat("Foley catheter inserted.\n")
}

function InsertPaCath() {
    UserInsertedCvpFlag = true;
    UserInsertedPaCathFlag = true;
    UserMonitorDisplayStr = "pap";
    SetMonitorButtons();
    CaseLogStr2 = CaseLogStr2.concat("Pulmonary artery catheter inserted.\n")
}

function DisplayNbp() {
    UserMonitorDisplayStr = "nbp";
    SetMonitorButtons();
    $("txtM").innerHTML = "";
    NbpTimer = UserNbpInterval * 60 - 1;
    UserNbpModeStr = "inflating";
    NbpM = 0
}

function DisplayAbp() {
    UserMonitorDisplayStr = "abp";
    SetMonitorButtons()
}

function DisplayCvp() {
    UserMonitorDisplayStr = "cvp";
    SetMonitorButtons()
}

function DisplayPap() {
    UserMonitorDisplayStr = "pap";
    SetMonitorButtons()
}

function DisplayPawp() {
    UserMonitorDisplayStr = "pawp";
    SetMonitorButtons();
    CaseLogStr2 = CaseLogStr2.concat("Pulmonary artery wedge pressure: " + CurrentState.papW.toFixed(0) + " mmHg\n")
}

function MeasureCo() {
    UserMonitorDisplayStr = "co";
    CoCurrentPoint = 0;           
	CoSweep = 0;
    P1Y2 = P1Baseline + 20;
    SetMonitorButtons();
    CaseLogStr2 = CaseLogStr2.concat("Cardiac output: " + CurrentState.cardiacOutput.toFixed(1) + " L/min\n")
}

function DisplayToF() {
    var iSucc;
    var tmpSuccNmb;
    var nmbStr1;
    var nmbStr2;
    var nmbStr3;
    var nmbStr4;
    iSucc = ConvertDrugKeyToIndex("Succinylcholine");
    tmpSuccNmb = DrugInfo.Drugs[iSucc].adminBolusLevel * DrugInfo.Drugs[iSucc].effectMagnitude / (DrugInfo.Drugs[iSucc].bolusE100 * CurrentCase.leanBodyMass);
    if (PddNmb < 0.4) {
        nmbStr1 = "Strong"
    } else if (PddNmb < 0.6) {
        nmbStr1 = "Moderate"
    } else if (PddNmb < 0.8) {
        nmbStr1 = "Weak"
    } else {
        nmbStr1 = "Absent"
    }
    if ((PddNmb > 0) && (tmpSuccNmb / PddNmb > 0.5)) {
        nmbStr2 = nmbStr1;
        nmbStr3 = nmbStr1;
        nmbStr4 = nmbStr1
    } else {
        if (PddNmb < 0.3) {
            nmbStr2 = "Strong"
        } else if (PddNmb < 0.5) {
            nmbStr2 = "Moderate"
        } else if (PddNmb < 0.7) {
            nmbStr2 = "Weak"
        } else {
            nmbStr2 = "Absent"
        }
        if (PddNmb < 0.2) {
            nmbStr3 = "Strong"
        } else if (PddNmb < 0.4) {
            nmbStr3 = "Moderate"
        } else if (PddNmb < 0.6) {
            nmbStr3 = "Weak"
        } else {
            nmbStr3 = "Absent"
        }
        if (PddNmb < 0.1) {
            nmbStr4 = "Strong"
        } else if (PddNmb < 0.3) {
            nmbStr4 = "Moderate"
        } else if (PddNmb < 0.5) {
            nmbStr4 = "Weak"
        } else {
            nmbStr4 = "Absent"
        }
    }
    $("pNerveStimResults").innerHTML = "T1: " + nmbStr1 + "<br>" + "T2: " + nmbStr2 + "<br>" + "T3: " + nmbStr3 + "<br>" + "T4: " + nmbStr4;
    CaseLogStr2 = CaseLogStr2.concat("Train of Four: " + nmbStr1 + ", " + nmbStr2 + ", " + nmbStr3 + ", " + nmbStr4 + "\n")
}

function DisplayTetanus() {
    var iSucc;
    var tmpSuccNmb;
    var nmbStr;
    iSucc = ConvertDrugKeyToIndex("Succinylcholine");
    tmpSuccNmb = DrugInfo.Drugs[iSucc].adminBolusLevel * DrugInfo.Drugs[iSucc].effectMagnitude / (DrugInfo.Drugs[iSucc].bolusE100 * CurrentCase.leanBodyMass);
    if ((PddNmb > 0) && (tmpSuccNmb / PddNmb > 0.5)) {
        if (PddNmb < 0.2) {
            nmbStr = "Strong response without fade."
        } else if (PddNmb < 0.4) {
            nmbStr = "Moderate response."
        } else if (PddNmb < 0.8) {
            nmbStr = "Weak response."
        } else {
            nmbStr = "No response."
        }
    } else {
        if (PddNmb < 0.2) {
            nmbStr = "Strong response without fade."
        } else if (PddNmb < 0.4) {
            nmbStr = "Moderate response with fade."
        } else if (PddNmb < 0.8) {
            nmbStr = "Weak response with fade."
        } else {
            nmbStr = "No response."
        }
    }
    $("pNerveStimResults").innerHTML = nmbStr;
    CaseLogStr2 = CaseLogStr2.concat("Tetanus: " + nmbStr + "\n")
}

function ShowAirwayScreen() {
	UserShowingCenter = "airway"; 
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divAirway1");
    $("divDisplayContent").appendChild(myDiv);
    $("divAirway1").innerHTML = "";
    var myP = document.createElement("p");
    myP.setAttribute("id", "pAirwayMan");
    myP.innerHTML = "Airway Maneuvers";
    myDiv.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnMask");
	myButton.classList.remove('disabled');
	myButton.style.pointerEvents = 'auto';
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnCricoid");
	myButton.classList.remove('disabled');
	myButton.style.pointerEvents = 'auto';
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnInsertOral");
    myButton.innerHTML = "Insert Oral Airway";
	myButton.classList.remove('disabled');
	myButton.style.pointerEvents = 'auto';
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnInsertNasal");
    myButton.innerHTML = "Insert Nasal Airway";
	myButton.classList.remove('disabled');
	myButton.style.pointerEvents = 'auto';
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnAdjustHead");
    myButton.innerHTML = "Adjust Head Position";
	myButton.classList.remove('disabled');
	myButton.style.pointerEvents = 'auto';
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnSuction");
    myButton.innerHTML = "Suction";
	myButton.classList.remove('disabled');
	myButton.style.pointerEvents = 'auto';
    myDiv.appendChild(myButton);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pAirwayComment");
    myP.innerHTML = "";
    myDiv.appendChild(myP);

    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divAirway2");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pIntubation");
    myP.innerHTML = "Intubation";
    myDiv.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnLma");
    myButton.innerHTML = "Place LMA...";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnLaryngoscopy");
    myButton.innerHTML = "Laryngoscopy ...";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnFiberoptic");
    myButton.innerHTML = "Fiberoptic ...";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnCrico");
    myButton.innerHTML = "Crico-otomy ...";
    myDiv.appendChild(myButton);

    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divAirway3");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pTitle"); 
    myP.hide();
    myDiv.appendChild(myP);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pTubeDepth"); 
    myP.hide();
    myP.innerHTML = "Depth:";
    myDiv.appendChild(myP);
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selTubeDepth");
    mySelect.hide();
    var tmpDepth;
    for (var i = 0; i <= 20; i++) {
        var myOption = document.createElement("option");
        tmpDepth = i + 10;
        myOption.innerHTML = tmpDepth.toFixed(0);
        myOption.setAttribute("value", tmpDepth);
        mySelect.appendChild(myOption)
    }
    myDiv.appendChild(mySelect); 
    var myP = document.createElement("p");
    myP.setAttribute("id", "pDepthUnits");
    myP.hide();
    myP.innerHTML = "cm";
    myDiv.appendChild(myP); 
    $("selTubeDepth").value = UserDepthTubeCurrent;
    var myP = document.createElement("p");
    myP.setAttribute("id", "pTubeDepthMsg");
    myP.hide();
    myP.innerHTML = "Tube depth is " + UserDepthTubeCurrent + " cm.";
    myDiv.appendChild(myP);
	
/* for Crico */
    var myP = document.createElement("p");
    myP.setAttribute("id", "pCrico"); 
    myP.hide();
    myP.innerHTML = "You performed the cricothyroidotomy successfully.  Air was aspirated through a 12 gauge IV catheter that you inserted through the cricothyroid membrane.";
    myDiv.appendChild(myP); 
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnCricoVent");
    myButton.hide();
    myButton.innerHTML = "Ventilate through catheter";
    myDiv.appendChild(myButton);  
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnCricoRemove");
    myButton.hide();
    myButton.innerHTML = "Remove catheter";
    myDiv.appendChild(myButton); 
	
/* for Fiberoptic */	
    var myImg = document.createElement("img");
    myImg.setAttribute("id", "imgFo");
    myImg.hide();
    myDiv.appendChild(myImg);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pFo");
    myP.hide();
    myDiv.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnFoContinue");
    myButton.hide();
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnFoCancel");
    myButton.hide();
    myDiv.appendChild(myButton);

/* for Laryngoscopy */
    var myImg = document.createElement("img");
    myImg.setAttribute("id", "imgLary");
	myImg.hide();
    myDiv.appendChild(myImg);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pLary");
	myP.hide();
    myDiv.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnLaryDo");
	myButton.hide();
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnLaryDoNot");
	myButton.hide();
    myDiv.appendChild(myButton);

    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnRemoveTube");
    myButton.hide();
    myButton.innerHTML = "Remove Tube ...";
    myDiv.appendChild(myButton);
	
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnRemoveConfirm");
    myButton.hide();
    myButton.innerHTML = "Confirm";
    myDiv.appendChild(myButton);
	
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnRemoveCancel");
    myButton.hide();
    myButton.innerHTML = "Cancel";
    myDiv.appendChild(myButton);
	
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnAirwayOk");
    myButton.hide();
    myButton.innerHTML = "OK";
    myDiv.appendChild(myButton);
	
/* for Lma */
	var myP = document.createElement("p");
	myP.setAttribute("id", "pLma");
	myP.hide();
	myDiv.appendChild(myP);  
	var myButton = document.createElement("button");
	myButton.setAttribute("id", "btnLmaOkay");
 	myButton.hide();
	myButton.innerHTML = "OK";
    myDiv.appendChild(myButton);  
	
    $("btnCricoid").observe("click", ClickBtnCricoid);
    $("btnAdjustHead").observe("click", ClickBtnAdjustHead);
    $("btnInsertOral").observe("click", ClickBtnInsertOral);
    $("btnInsertNasal").observe("click", ClickBtnInsertNasal);
    $("btnMask").observe("click", ClickBtnMask);
    $("btnLma").observe("click", ClickBtnLma);
    $("btnSuction").observe("click", ClickBtnSuction);
    $("btnLaryngoscopy").observe("click", ClickBtnLaryngoscopy);
    $("btnFiberoptic").observe("click", ClickBtnFiberoptic);
    $("btnCrico").observe("click", ClickBtnCrico);
    $("selTubeDepth").observe("change", SetTubeDepth);
    $("btnLaryDo").observe("click", ClickBtnLaryDo);
    $("btnLaryDoNot").observe("click", ClickBtnLaryDoNot);
    $("btnRemoveTube").observe("click", ClickBtnRemoveTube);
    $("btnRemoveConfirm").observe("click", ClickBtnRemoveConfirm);
    $("btnRemoveCancel").observe("click", ClickBtnRemoveCancel);
    $("btnFoContinue").observe("click", ClickBtnFoContinue);
    $("btnFoCancel").observe("click", ClickBtnFoCancel);
    $("btnCricoVent").observe("click", ClickBtnCricoVent);
    $("btnCricoRemove").observe("click", ClickBtnCricoRemove);
    $("btnAirwayOk").observe("click", ClickBtnAirwayOk);
    SetAirwayButtons();
}

function SetAirwayButtons() {
    if (UserDoingCricoidFlag) {
        $("btnCricoid").innerHTML = "Remove Cricoid"
    } else {
        $("btnCricoid").innerHTML = "Place Cricoid"
    }
    if (UserAirwayStr == "none") {
		$("btnCricoid").classList.remove('disabled');
		$("btnCricoid").style.pointerEvents = 'auto';
        $("btnMask").innerHTML = "Place Mask";
		$("btnMask").classList.remove('disabled');
		$("btnMask").style.pointerEvents = 'auto';
        $("btnLma").innerHTML = "Place LMA";
		$("btnLma").classList.remove('disabled');
		$("btnLma").style.pointerEvents = 'auto';
		$("btnLaryngoscopy").classList.remove('disabled');
		$("btnLaryngoscopy").style.pointerEvents = 'auto';
		$("btnFiberoptic").classList.remove('disabled');
		$("btnFiberoptic").style.pointerEvents = 'auto';
		$("btnCrico").classList.remove('disabled');
		$("btnCrico").style.pointerEvents = 'auto';
		
    } else if (UserAirwayStr == "mask") {
		$("btnCricoid").classList.remove('disabled');
		$("btnCricoid").style.pointerEvents = 'auto';
        $("btnMask").innerHTML = "Remove Mask";
		$("btnMask").classList.remove('disabled');
		$("btnMask").style.pointerEvents = 'auto';
        $("btnLma").innerHTML = "Place LMA";
		$("btnLma").classList.remove('disabled');
		$("btnLma").style.pointerEvents = 'auto';
		$("btnLaryngoscopy").classList.remove('disabled');
		$("btnLaryngoscopy").style.pointerEvents = 'auto';
		$("btnFiberoptic").classList.remove('disabled');
		$("btnFiberoptic").style.pointerEvents = 'auto';
		$("btnCrico").classList.remove('disabled');
		$("btnCrico").style.pointerEvents = 'auto';
		
    } else if (UserAirwayStr == "lma") {
		$("btnCricoid").classList.add('disabled');
		$("btnCricoid").style.pointerEvents = 'none';
        $("btnMask").innerHTML = "Place Mask";
		$("btnMask").classList.add('disabled');
		$("btnMask").style.pointerEvents = 'none';
        $("btnLma").innerHTML = "Remove LMA";
		$("btnLma").classList.remove('disabled');
		$("btnLma").style.pointerEvents = 'auto';
		$("btnLaryngoscopy").classList.add('disabled');
		$("btnLaryngoscopy").style.pointerEvents = 'none';
		$("btnFiberoptic").classList.remove('disabled');
		$("btnFiberoptic").style.pointerEvents = 'auto';
		$("btnCrico").classList.remove('disabled');
		$("btnCrico").style.pointerEvents = 'auto';
		
    } else if (UserAirwayStr == "tube") {
		$("btnCricoid").classList.remove('disabled');
		$("btnCricoid").style.pointerEvents = 'auto';
        $("btnMask").innerHTML = "Place Mask";
		$("btnMask").classList.add('disabled');
		$("btnMask").style.pointerEvents = 'none';
        $("btnLma").innerHTML = "Place LMA";
		$("btnLma").classList.add('disabled');
		$("btnLma").style.pointerEvents = 'none';
		$("btnLaryngoscopy").classList.remove('disabled');
		$("btnLaryngoscopy").style.pointerEvents = 'auto';
		$("btnFiberoptic").classList.remove('disabled');
		$("btnFiberoptic").style.pointerEvents = 'auto';
		$("btnCrico").classList.add('disabled');
		$("btnCrico").style.pointerEvents = 'none';
		$("pTitle").innerHTML = "Endotracheal Tube";
        $("pTitle").show();
        $("selTubeDepth").value = UserDepthTubeCurrent;
		$("imgLary").hide();
		$("pLary").hide();
		$("btnLaryDo").hide();
		$("btnLaryDoNot").hide();
		$("pTubeDepth").show(); 
		$("selTubeDepth").show();
		$("pDepthUnits").show();
		$("pTubeDepthMsg").show();
		$("btnRemoveTube").show();
		
    } else if (UserAirwayStr == "crico") {
		$("btnCricoid").classList.remove('disabled');
		$("btnCricoid").style.pointerEvents = 'auto';
        $("btnMask").innerHTML = "Place Mask";
	    $("btnMask").classList.add('disabled');
		$("btnMask").style.pointerEvents = 'none';
        $("btnLma").innerHTML = "Place LMA";
		$("btnLma").classList.add('disabled');
		$("btnLma").style.pointerEvents = 'none';
		$("btnLaryngoscopy").classList.remove('disabled');
		$("btnLaryngoscopy").style.pointerEvents = 'auto';
		$("btnFiberoptic").classList.remove('disabled');
		$("btnFiberoptic").style.pointerEvents = 'auto';
		$("btnCrico").classList.add('disabled');
		$("btnCrico").style.pointerEvents = 'none';
    }
	$("btnInsertOral").classList.remove('disabled');
	$("btnInsertOral").style.pointerEvents = 'auto';
	$("btnInsertNasal").classList.remove('disabled');
	$("btnInsertNasal").style.pointerEvents = 'auto';
	$("btnAdjustHead").classList.remove('disabled');
	$("btnAdjustHead").style.pointerEvents = 'auto';
	$("btnSuction").classList.remove('disabled');
	$("btnSuction").style.pointerEvents = 'auto';
}

function DisableAirwayButtons() {
	$("btnMask").classList.add('disabled');
	$("btnMask").style.pointerEvents = 'none';
	$("btnCricoid").classList.add('disabled');
	$("btnCricoid").style.pointerEvents = 'none';
	$("btnLma").classList.add('disabled');
	$("btnLma").style.pointerEvents = 'none';
	$("btnLaryngoscopy").classList.add('disabled');
	$("btnLaryngoscopy").style.pointerEvents = 'none';
	$("btnFiberoptic").classList.add('disabled');
	$("btnFiberoptic").style.pointerEvents = 'none';
	$("btnCrico").classList.add('disabled');
	$("btnCrico").style.pointerEvents = 'none';
	$("btnInsertOral").classList.add('disabled');
	$("btnInsertOral").style.pointerEvents = 'none';
	$("btnInsertNasal").classList.add('disabled');
	$("btnInsertNasal").style.pointerEvents = 'none';
	$("btnAdjustHead").classList.add('disabled');
	$("btnAdjustHead").style.pointerEvents = 'none';
	$("btnSuction").classList.add('disabled');
	$("btnSuction").style.pointerEvents = 'none';
}

function ClickBtnAirwayOk() {
    UserConnectedFlag = true;
    $("pTitle").hide();
    $("imgLary").hide();
    $("pLary").hide();
    $("btnLaryDo").hide();
    $("btnLaryDoNot").hide();
    $("btnAirwayOk").hide();
    $("imgFo").hide();
    $("pFo").hide();
    $("btnFoContinue").hide();
    $("btnFoCancel").hide();

    $("pTubeDepth").show(); 
    $("selTubeDepth").show();
    $("pDepthUnits").show();
    $("pTubeDepthMsg").show();
    $("btnRemoveTube").show();

    if (UserDoingCricoidFlag) {
        $("imgPatient").src = "app/images/" + UserImageStr + "/tubP_" + CurrentCase.imageSet + ".jpg"
		LastPatientImageStr = "/tubP_" + CurrentCase.imageSet + ".jpg";
    } else {
        $("imgPatient").src = "app/images/" + UserImageStr + "/tub_" + CurrentCase.imageSet + ".jpg"
		LastPatientImageStr = "/tub_" + CurrentCase.imageSet + ".jpg";
    }
    EnableSideMenu();
    SetAirwayButtons();
}

function ClickBtnCrico() {
    DisableSideMenu();
    $("pAirwayComment").innerHTML = "";
	$("pTitle").innerHTML = "Cricothyroidotomy";
	$("pTitle").show();
    $("pCrico").show();
    $("btnCricoVent").show();
    $("btnCricoRemove").show();
    $("imgPatient").src = "app/images/" + UserImageStr + "/doCri_" + CurrentCase.imageSet + ".jpg";
	LastPatientImageStr = "/doCri_" + CurrentCase.imageSet + ".jpg";
    DisableSideMenu();
    DisableAirwayButtons(); 
}

function ClickBtnCricoRemove() {
    CaseLogStr2 = CaseLogStr2.concat("Cricothyroidotomy removed.\n");
    UserAirwayStr = "none";
    $("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg";
	LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
    UserConnectedFlag = false;
    UserBreathModeStr = "spontaneous";
	$("pTitle").hide();
    $("pCrico").hide();
    $("btnCricoVent").hide();
    $("btnCricoRemove").hide();
    EnableSideMenu();
    SetAirwayButtons();
}

function ClickBtnCricoVent() {
	$("pTitle").hide();
    $("pCrico").hide();
    $("btnCricoVent").hide();
    $("btnCricoRemove").hide();
    CaseLogStr2 = CaseLogStr2.concat("Cricothyroidotomy successfully performed.\n");
    UserAirwayStr = "crico";
    $("imgPatient").src = "app/images/" + UserImageStr + "/cri_" + CurrentCase.imageSet + ".jpg";
	LastPatientImageStr = "/cri_" + CurrentCase.imageSet + ".jpg";
    UserConnectedFlag = true;
    UserConnectedThisCaseFlag = true;
    UserBreathModeStr = "spontaneous";
	RecordHeader();  
    ShowCaseLogScreen();
}

function ClickBtnCricoid() {
    if (UserDoingCricoidFlag) {
        $("pAirwayComment").innerHTML = "Cricoid pressure removed.";
        CaseLogStr2 = CaseLogStr2.concat("Cricoid pressure removed.\n");
        UserDoingCricoidFlag = false;
        $("btnCricoid").innerHTML = "Place Cricoid";
        if (UserAirwayStr == "none") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
        } else if (UserAirwayStr == "mask") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/msk_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/msk_" + CurrentCase.imageSet + ".jpg";
        } else if (UserAirwayStr == "lma") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/lma_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/lma_" + CurrentCase.imageSet + ".jpg";
        } else if (UserAirwayStr == "tube") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/tub_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/tub_" + CurrentCase.imageSet + ".jpg";
        } else if (UserAirwayStr == "crico") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/cri_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/cri_" + CurrentCase.imageSet + ".jpg";
        }
    } else {
        $("pAirwayComment").innerHTML = "Cricoid pressure placed.";
        CaseLogStr2 = CaseLogStr2.concat("Cricoid pressure placed.\n");
        UserDoingCricoidFlag = true;
        $("btnCricoid").innerHTML = "Remove Cricoid";
        if (UserAirwayStr == "none") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/clrP_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/clrP_" + CurrentCase.imageSet + ".jpg";
        } else if (UserAirwayStr == "mask") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/mskP_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/mskP_" + CurrentCase.imageSet + ".jpg";
        } else if (UserAirwayStr == "lma") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/lma_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/lma_" + CurrentCase.imageSet + ".jpg";
        } else if (UserAirwayStr == "tube") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/tubP_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/tubP_" + CurrentCase.imageSet + ".jpg";
        } else if (UserAirwayStr == "crico") {
            $("imgPatient").src = "app/images/" + UserImageStr + "/cri_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/cri_" + CurrentCase.imageSet + ".jpg";
        }
    }
}

function ClickBtnFiberoptic() {
    $("pAirwayComment").innerHTML = "";
	$("pTitle").innerHTML = "Fiberoptic View";
	$("pTitle").show();
    $("pTubeDepth").hide(); 
    $("selTubeDepth").hide();
    $("pDepthUnits").hide();
    $("pTubeDepthMsg").hide();
    $("btnRemoveTube").hide();

    UserBreathModeStr = "spontaneous";
    UserConnectedFlag = false;
    UserDoingCricoidFlag = false;
    UserTriedFoFlag = true;

    $("imgFo").show();
    $("pFo").show();
	
    if (UserAirwayStr == "tube") {
        UserConnectedFlag = true;
        UserConnectedThisCaseFlag = true;
        $("imgPatient").src = "app/images/" + UserImageStr + "/tub_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/tub_" + CurrentCase.imageSet + ".jpg";
        CaseLogStr2 = CaseLogStr2.concat("Fiberoptic visualization performed through endotracheal tube.\n")
    } else if (UserAirwayStr == "lma") {
        UserConnectedFlag = true;
        UserConnectedThisCaseFlag = true;
        $("imgPatient").src = "app/images/" + UserImageStr + "/lma_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/lma_" + CurrentCase.imageSet + ".jpg";
        CaseLogStr2 = CaseLogStr2.concat("Fiberoptic visualization performed through LMA.\n")
    } else {
        UserConnectedFlag = false;
        UserAirwayStr = "none";
        $("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
        CaseLogStr2 = CaseLogStr2.concat("Fiberoptic visualization performed.\n")
    }

    if (UserAirwayStr == "lma") {
        $("imgPatient").src = "app/images/" + UserImageStr + "/doFoLma_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/doFoLma_" + CurrentCase.imageSet + ".jpg";
        $("imgFo").src = "app/images/fo_lma.jpg";
        $("pFo").innerHTML = "The glottic opening is clearly visualized beyond the LMA.";
        $("btnFoContinue").innerHTML = "Place Tube";
        $("btnFoCancel").innerHTML = "Do NOT";
        $("btnFoContinue").show();
        $("btnFoCancel").show();
        $("btnAirwayOk").hide();
    } else if (PrpTubeStatusStr == "tubeInTrachea") {
        $("imgPatient").src = "app/images/" + UserImageStr + "/doFoTub_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/doFoTub_" + CurrentCase.imageSet + ".jpg";
        if (CurrentState.sputumAmount == 0) {
            $("imgFo").src = "app/images/fo_carina.jpg";
            $("pFo").innerHTML = "The carina is clearly visualized beyond the tip of the tube."
        } else {
            $("imgFo").src = "app/images/fo_secretions.jpg";
            $("pFo").innerHTML = "Thick secretions are obstructing the view."
        }
        $("btnFoContinue").innerHTML = "Place Tube";
        $("btnFoCancel").innerHTML = "Do NOT";
        $("btnFoContinue").hide();
        $("btnFoCancel").hide();
        $("btnAirwayOk").show();
    } else if (PrpTubeStatusStr == "tubeInRightMainstem") {
        $("imgPatient").src = "app/images/" + UserImageStr + "/doFoTub_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/doFoTub_" + CurrentCase.imageSet + ".jpg";
        $("imgFo").src = "app/images/fo_rightmainstem.jpg";
        $("pFo").innerHTML = "The tube is in the right mainstem bronchus.";
        $("btnFoContinue").hide();
        $("btnFoCancel").hide();
        $("btnAirwayOk").show();
    } else if (UserAirwayStr == "tube") {
        $("imgPatient").src = "app/images/" + UserImageStr + "/doFoTub_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/doFoTub_" + CurrentCase.imageSet + ".jpg";
        $("imgFo").src = "app/images/fo_esophagus.jpg";
        $("pFo").innerHTML = "The tube is not in the trachea.";
        $("btnFoContinue").hide();
        $("btnFoCancel").hide();
        $("btnAirwayOk").show();
    } else {
        $("imgPatient").src = "app/images/" + UserImageStr + "/doFo_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/doFo_" + CurrentCase.imageSet + ".jpg";
        $("imgFo").src = "app/images/fo_carina.jpg";
        $("pFo").innerHTML = "You passed the vocal cords and can clearly see the carina.";
        $("btnFoContinue").innerHTML = "Place Tube";
        $("btnFoCancel").innerHTML = "Do NOT";
        $("btnFoContinue").show();
        $("btnFoCancel").show();
        $("btnAirwayOk").hide();
    }
    UserSuctionedFlag = true;
    UserCheckedTubeFlag = true
    DisableSideMenu();
    DisableAirwayButtons(); 
}

function ClickBtnFoContinue() {
    $("pTitle").hide();
    $("imgFo").hide();
    $("pFo").hide();
    $("btnFoContinue").hide();
    $("btnFoCancel").hide();
    $("btnAirwayOk").hide();

    $("imgPatient").src = "app/images/" + UserImageStr + "/tub_" + CurrentCase.imageSet + ".jpg";
 	LastPatientImageStr = "/tub_" + CurrentCase.imageSet + ".jpg";
    CaseLogStr2 = CaseLogStr2.concat("Endotracheal tube placed with fiberoptic visualization.\n");
    UserAirwayStr = "tube";
    PrpTubeStatusStr = "tubeInTrachea";
    UserDepthTubeCurrent = CurrentCase.depthTubeInitial;
    $("selTubeDepth").value = UserDepthTubeCurrent;
    $("pTubeDepthMsg").innerHTML = "Tube depth is " + UserDepthTubeCurrent + " cm";
    UserConnectedFlag = true;
    UserConnectedThisCaseFlag = true;
    UserBreathModeStr = "spontaneous";

    $("pTubeDepth").show(); 
    $("selTubeDepth").show();
    $("pDepthUnits").show();
    $("pTubeDepthMsg").show();
    $("btnRemoveTube").show();

    EnableSideMenu();
    SetAirwayButtons();
}

function ClickBtnFoCancel() {
    $("pTitle").hide();
    $("imgFo").hide();
    $("pFo").hide();
    $("btnFoContinue").hide();
    $("btnFoCancel").hide();

    UserBreathModeStr = "spontaneous";
 
    if (UserAirwayStr == "tube") {
        UserConnectedFlag = true;
        UserConnectedThisCaseFlag = true;
        $("imgPatient").src = "app/images/" + UserImageStr + "/tub_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/tub_" + CurrentCase.imageSet + ".jpg";
    } else if (UserAirwayStr == "lma") {
        UserConnectedFlag = true;
        UserConnectedThisCaseFlag = true;
        $("imgPatient").src = "app/images/" + UserImageStr + "/lma_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/lma_" + CurrentCase.imageSet + ".jpg";
    } else {
        UserConnectedFlag = false;
        UserAirwayStr = "none";
        $("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
    }

    EnableSideMenu();
    SetAirwayButtons();
}

/* -----------------------------------------------------------------
Note: State can change between ClickBtnLaryngoscopy and BtnLaryDo
------------------------------------------------------------------ */	  
function ClickBtnLaryngoscopy() {
    $("pAirwayComment").innerHTML = "";
	$("pTitle").innerHTML = "Laryngoscopy View";
	$("pTitle").show();
    $("pTubeDepth").hide(); 
    $("selTubeDepth").hide();
    $("pDepthUnits").hide();
    $("pTubeDepthMsg").hide();
    $("btnRemoveTube").hide();
	
	AwLaryTubeSuccess = CurrentState.laryTubeSuccess;
    UserConnectedFlag = false;
    if (UserDoingCricoidFlag) {
        $("imgPatient").src = "app/images/" + UserImageStr + "/doTubP_" + CurrentCase.imageSet + ".jpg"
 		LastPatientImageStr = "/doTubP_" + CurrentCase.imageSet + ".jpg";
    } else {
        $("imgPatient").src = "app/images/" + UserImageStr + "/doTub_" + CurrentCase.imageSet + ".jpg"
 		LastPatientImageStr = "/doTub_" + CurrentCase.imageSet + ".jpg";
    }

    if ((PrpTubeStatusStr == "tubeInEsophagus") || (PrpTubeStatusStr == "tubeAboveCords")) {
        $("imgLary").src = "app/images/lary_4.jpg";
        $("pLary").innerHTML = "The tube IS NOT between the vocal cords.";
        CaseLogStr2 = CaseLogStr2.concat("Laryngoscopy shows tube is NOT between vocal cords.\n");
		$("imgLary").show();
		$("pLary").show();
		$("btnLaryDo").hide();
        $("btnLaryDoNot").hide();
        $("btnAirwayOk").show();
    } else if (UserAirwayStr == "tube") {
        $("imgLary").src = "app/images/lary_3.jpg";
        $("pLary").innerHTML = "The tube IS between the vocal cords.";
        CaseLogStr2 = CaseLogStr2.concat("Laryngoscopy shows tube is between vocal cords.\n");
		$("imgLary").show();
		$("pLary").show();
		$("btnLaryDo").hide();
        $("btnLaryDoNot").hide();
        $("btnAirwayOk").show();
    } else {
        UserAirwayStr = "none";
        UserBreathModeStr = "spontaneous";
        UserTriedLaryTubeFlag = true
		$("btnLaryDo").innerHTML = "Place Tube";
		$("btnLaryDoNot").innerHTML = "Do NOT";
        if (CurrentState.laryTubeSuccess == 1) {
            $("pLary").innerHTML = "There is a Grade 1 view of the larynx.";
            $("imgLary").src = "app/images/lary_1.jpg";
			CaseLogStr2 = CaseLogStr2.concat("Laryngoscopy: Grade 1 view of larynx\n");
        } else if (CurrentState.laryTubeSuccess == -1) {
            $("pLary").innerHTML = "There is a Grade 4 view of the larynx.";
            $("imgLary").src = "app/images/lary_2.jpg";
			CaseLogStr2 = CaseLogStr2.concat("Laryngoscopy: Grade 4 view of larynx\n");
        } else if (CurrentState.laryTubeSuccess == -2) {
            $("pLary").innerHTML = "There is a good view of the vocal cords.";
            $("imgLary").src = "app/images/lary_1.jpg";
			CaseLogStr2 = CaseLogStr2.concat("Laryngoscopy: Good view of larynx\n");
        } else if (CurrentState.laryTubeSuccess == 0) {
            $("pLary").innerHTML = "There is a poor view because the patient is coughing.";
            $("imgLary").src = "app/images/lary_2.jpg";
			CaseLogStr2 = CaseLogStr2.concat("Laryngoscopy: Poor view of larynx due to coughing\n");
        } else {
            $("pLary").innerHTML = "There is a good view of the larynx.";
            $("imgLary").src = "app/images/lary_1.jpg";
			CaseLogStr2 = CaseLogStr2.concat("Laryngoscopy: Good view of larynx\n");
        }
		$("imgLary").show();
		$("pLary").show();
		$("btnLaryDo").show();
        $("btnLaryDoNot").show();
        $("btnAirwayOk").hide();

    }
    DisableSideMenu();
    DisableAirwayButtons(); 
}

function ClickBtnLaryDo() {
    $("pTitle").hide();
    $("imgLary").hide();
    $("pLary").hide();
    $("btnLaryDo").hide();
    $("btnLaryDoNot").hide();

	UserTriedLaryTubeFlag = true;
	UserAirwayStr = "tube";
	SetAirwayButtons();
	UserConnectedFlag = true;
	UserConnectedThisCaseFlag = true;
	if (AwLaryTubeSuccess == 1) {
		PrpTubeStatusStr = "tubeInTrachea";
		CaseLogStr2 = CaseLogStr2.concat("Endotracheal tube inserted via direct laryngoscopy.\n");
		UserBreathModeStr = "spontaneous";
		UserDepthTubeCurrent = CurrentCase.depthTubeInitial;
		$("selTubeDepth").value = UserDepthTubeCurrent;
		$("pTubeDepthMsg").innerHTML = "Tube depth is " + UserDepthTubeCurrent + " cm";
	} else {
		PrpTubeStatusStr = "tubeInEsophagus";
		CaseLogStr2 = CaseLogStr2.concat("Esophageal intubation!!\n");
		UserBreathModeStr = "spontaneous";
		UserDepthTubeCurrent = CurrentCase.depthTubeInitial;
		$("selTubeDepth").value = UserDepthTubeCurrent;
		$("pTubeDepthMsg").innerHTML = "Tube depth is " + UserDepthTubeCurrent + " cm";
	}
	if (UserDoingCricoidFlag) {
		$("imgPatient").src = "app/images/" + UserImageStr + "/tubP_" + CurrentCase.imageSet + ".jpg"
 		LastPatientImageStr = "/tubP_" + CurrentCase.imageSet + ".jpg";
	} else {
		$("imgPatient").src = "app/images/" + UserImageStr + "/tub_" + CurrentCase.imageSet + ".jpg"
 		LastPatientImageStr = "/tub_" + CurrentCase.imageSet + ".jpg";
	}

    $("pTubeDepth").show(); 
    $("selTubeDepth").show();
    $("pDepthUnits").show();
    $("pTubeDepthMsg").show();
    $("btnRemoveTube").show();

    EnableSideMenu();
    SetAirwayButtons();
}

function ClickBtnLaryDoNot() {
    $("pTitle").hide();
    $("imgLary").hide();
    $("pLary").hide();
    $("btnLaryDo").hide();
    $("btnLaryDoNot").hide();

	UserConnectedFlag = false;
	UserAirwayStr = "none";
	if (UserDoingCricoidFlag) {
		$("imgPatient").src = "app/images/" + UserImageStr + "/clrP_" + CurrentCase.imageSet + ".jpg"
 		LastPatientImageStr = "/clrP_" + CurrentCase.imageSet + ".jpg";
	} else {
		$("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg"
 		LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
	}

    EnableSideMenu();
    SetAirwayButtons();
}



function ClickBtnLma() {
    $("pAirwayComment").innerHTML = "";
    UserBreathModeStr = "spontaneous";
    UserConnectedFlag = false;
    if ((UserAirwayStr == "none") || (UserAirwayStr == "mask")) {
        UserTriedLmaFlag = true;
        UserConnectedFlag = false;
		$("pTitle").innerHTML = "LMA Insertion";
		$("pTitle").show();
		$("pLma").show();
		$("btnLmaOkay").show();
        $("btnLmaOkay").observe("click", ClickBtnLmaOkay);
        $("imgPatient").src = "app/images/" + UserImageStr + "/doLma_" + CurrentCase.imageSet + ".jpg";
 		LastPatientImageStr = "/doLma_" + CurrentCase.imageSet + ".jpg";
        if (CurrentState.lmaSuccessFlag) {
            CaseLogStr2 = CaseLogStr2.concat("LMA inserted.\n");
            UserAirwayStr = "lma";
            $("pLma").innerHTML = "The LMA is easy to insert."
        } else {
            CaseLogStr2 = CaseLogStr2.concat("Unable to insert LMA.\n");
            UserAirwayStr = "none";
            $("pLma").innerHTML = "The LMA cannot be inserted."
        }
		DisableSideMenu();
		DisableAirwayButtons(); 
    } else {
        CaseLogStr2 = CaseLogStr2.concat("LMA removed.\n");
        UserAirwayStr = "none";
        $("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg"
 		LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
		EnableSideMenu();
		SetAirwayButtons();
    }
}

function ClickBtnLmaOkay() {
    UserTriedLmaFlag = true;
    EnableSideMenu();
    UserDoingCricoidFlag = false;
    if (UserAirwayStr == "lma") {
        UserConnectedFlag = true;
        UserConnectedThisCaseFlag = true;
        $("imgPatient").src = "app/images/" + UserImageStr + "/lma_" + CurrentCase.imageSet + ".jpg"
		LastPatientImageStr = "/lma_" + CurrentCase.imageSet + ".jpg";
    } else {
        $("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg"
		LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
    }
    SetAirwayButtons();
    EnableSideMenu();
    SetAirwayButtons();
	$("pTitle").hide();
	$("pLma").hide();
	$("btnLmaOkay").hide();
}

function ClickBtnMask() {
    $("pAirwayComment").innerHTML = "";
    if (UserAirwayStr == "none") {
        CaseLogStr2 = CaseLogStr2.concat("Anesthesia mask placed.\n");
        UserAirwayStr = "mask";
        SetAirwayButtons();
        UserConnectedFlag = true;
        UserConnectedThisCaseFlag = true;
        if (UserDoingCricoidFlag) {
            $("imgPatient").src = "app/images/" + UserImageStr + "/mskP_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/mskP_" + CurrentCase.imageSet + ".jpg";
        } else {
            $("imgPatient").src = "app/images/" + UserImageStr + "/msk_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/msk_" + CurrentCase.imageSet + ".jpg";
        }
    } else if (UserAirwayStr == "mask") {
        CaseLogStr2 = CaseLogStr2.concat("Anesthesia mask removed.\n");
        UserAirwayStr = "none";
        SetAirwayButtons();
        UserConnectedFlag = false;
        if (UserDoingCricoidFlag) {
            $("imgPatient").src = "app/images/" + UserImageStr + "/clrP_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/clrP_" + CurrentCase.imageSet + ".jpg";
        } else {
            $("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg"
			LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
        }
    }
}

function ClickBtnRemoveTube() {
    $("btnRemoveConfirm").show();
    $("btnRemoveCancel").show()
}

function ClickBtnRemoveConfirm() {
    UserAirwayStr = "none";
    SetAirwayButtons();
    UserConnectedFlag = false;
    if (UserDoingCricoidFlag) {
        $("imgPatient").src = "app/images/" + UserImageStr + "/clrP_" + CurrentCase.imageSet + ".jpg"
		LastPatientImageStr = "/clrP_" + CurrentCase.imageSet + ".jpg";
    } else {
        $("imgPatient").src = "app/images/" + UserImageStr + "/clr_" + CurrentCase.imageSet + ".jpg"
		LastPatientImageStr = "/clr_" + CurrentCase.imageSet + ".jpg";
    }
    CaseLogStr2 = CaseLogStr2.concat("Endotracheal tube removed.\n")

    $("pTitle").hide(); 
    $("pTubeDepth").hide(); 
    $("selTubeDepth").hide();
    $("pDepthUnits").hide();
    $("pTubeDepthMsg").hide();
    $("btnRemoveTube").hide();

    $("btnRemoveTube").hide();
    $("btnRemoveConfirm").hide();
    $("btnRemoveCancel").hide();
}

function ClickBtnRemoveCancel() {
    if (UserDoingCricoidFlag) {
        $("imgPatient").src = "app/images/" + UserImageStr + "/tubP_" + CurrentCase.imageSet + ".jpg";
		LastPatientImageStr = "/tubP_" + CurrentCase.imageSet + ".jpg";
    } else {
        $("imgPatient").src = "app/images/" + UserImageStr + "/tub_" + CurrentCase.imageSet + ".jpg";
		LastPatientImageStr = "/tub_" + CurrentCase.imageSet + ".jpg";
    }

    $("btnRemoveConfirm").hide();
    $("btnRemoveCancel").hide()
}

function ClickBtnAdjustHead() {
    $("pAirwayComment").innerHTML = "Head position adjusted.";
    UserAdjustedHeadFlag = true;
    CaseLogStr2 = CaseLogStr2.concat("Head position adjusted.\n")
}

function ClickBtnInsertOral() {
    $("pAirwayComment").innerHTML = "Oral airway inserted.";
    UserInsertedOralFlag = true;
    CaseLogStr2 = CaseLogStr2.concat("Oral airway inserted.\n")
}

function ClickBtnInsertNasal() {
    $("pAirwayComment").innerHTML = "Nasal airway inserted.";
    UserInsertedNasalFlag = true;
    CaseLogStr2 = CaseLogStr2.concat("Nasal airway inserted.\n")
}

function ClickBtnSuction() {
    if (CurrentState.sputumAmount == 0) {
        $("pAirwayComment").innerHTML = "Airway suctioned - minimal secretions.";
        CaseLogStr2 = CaseLogStr2.concat("Airway suctioned - minimal secretions.\n")
    } else if (CurrentState.sputumAmount == 1) {
        $("pAirwayComment").innerHTML = "Airway suctioned - moderate secretions.";
        CaseLogStr2 = CaseLogStr2.concat("Airway suctioned - moderate secretions.\n")
    } else {
        $("pAirwayComment").innerHTML = "Airway suctioned - copious, thick secretions.";
        CaseLogStr2 = CaseLogStr2.concat("Airway suctioned - copious, thick secretions.\n")
    }
    UserSuctionedFlag = true
}

function SetTubeDepth() {
    $("pAirwayComment").innerHTML = "";
    UserCheckedTubeFlag = true;
    UserDepthTubeCurrent = $("selTubeDepth").value;
    $("pTubeDepthMsg").innerHTML = "Tube taped at " + UserDepthTubeCurrent + " cm.";
    CaseLogStr2 = CaseLogStr2.concat("Tube taped at " + UserDepthTubeCurrent + " cm\n")
}




function ShowBreathingScreen() {
	UserShowingCenter = "breathing"; 
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
	
	var myDiv1 = document.createElement("div");
    myDiv1.setAttribute("id", "divBreathing1");
    $("divDisplayContent").appendChild(myDiv1);
	
    var myP = document.createElement("p");
    myP.setAttribute("id", "pBreathMode");
    myP.innerHTML = "Mode of Breathing";
    myDiv1.appendChild(myP);
	
    var myRadio = document.createElement("input");
    myRadio.setAttribute("id", "rbSpontaneous");
    myRadio.setAttribute("type", "radio");
    myRadio.setAttribute("name", "breathingModes");
    myRadio.setAttribute("value", "spontaneous");
    myDiv1.appendChild(myRadio);                 

    var myLabel = document.createElement("label");
    myLabel.setAttribute("id", "labelSpontaneous");
	myLabel.innerHTML = "Spontaneous";
    myLabel.htmlFor = "rbSpontaneous";
//    myLabel.appendChild(document.createTextNode("Spontaneous")); 
    myDiv1.appendChild(myLabel);
	
    var myRadio = document.createElement("input");
    myRadio.setAttribute("id", "rbBagControl");
    myRadio.setAttribute("type", "radio");
    myRadio.setAttribute("name", "breathingModes");
    myRadio.setAttribute("value", "bagControl");
    myDiv1.appendChild(myRadio);
	
    var myLabel = document.createElement("label");
    myLabel.setAttribute("id", "labelBagControl");
	myLabel.innerHTML = "Bag Assist/Control";
	myLabel.htmlFor = "rbBagControl";
//    myLabel.appendChild(document.createTextNode("Bag Assist/Control"));
    myDiv1.appendChild(myLabel);                
	
    var myRadio = document.createElement("input");
    myRadio.setAttribute("id", "rbVentilator");
    myRadio.setAttribute("type", "radio");
    myRadio.setAttribute("name", "breathingModes");
    myRadio.setAttribute("value", "ventilator");
    myDiv1.appendChild(myRadio);                // was divRb
	
    var myLabel = document.createElement("label");
    myLabel.setAttribute("id", "labelVentilator");
	myLabel.innerHTML = "Ventilator";
    myLabel.htmlFor = "rbVentilator";
//    myLabel.appendChild(document.createTextNode("Ventilator"));
    myDiv1.appendChild(myLabel);            


	
    var myDiv2 = document.createElement("div");
    myDiv2.setAttribute("id", "divBreathing2");
    $("divDisplayContent").appendChild(myDiv2);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pVentSettings");
    myP.innerHTML = "Ventilation Settings";
    myDiv2.appendChild(myP);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pTv");
    myP.innerHTML = "Tidal Volume:";
    myDiv2.appendChild(myP);
    var myList = document.createElement("select");
    myList.setAttribute("id", "selTv");
    myList.setAttribute("name", "selTv");
    myP.appendChild(myList);                       /* note myP is pTv */
    var tmpPedsScaler;
    if (CurrentCase.leanBodyMass > 19) {
        tmpPedsScaler = 1
    } else if (CurrentCase.leanBodyMass > 9) {
        tmpPedsScaler = 5
    } else {
        tmpPedsScaler = 10
    }
    var tmpValue;
    for (var i = 1; i <= 55; i++) {
        if (i < 11) {
            tmpValue = (i * 10) / tmpPedsScaler;
        } else {
            tmpValue = (i * 20 - 100) / tmpPedsScaler; 
        }
        var myOption = document.createElement("option");
        myOption.innerHTML = tmpValue;
        myOption.setAttribute("value", parseFloat(tmpValue));
        myList.appendChild(myOption)
    }
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "tidalvolume";
    myLabel.appendChild(document.createTextNode("mL"));
    myP.appendChild(myLabel);                    /* note myP is pTv */
	
    var myP = document.createElement("p");
    myP.setAttribute("id", "pRr");
    myP.innerHTML = "Resp Rate:";
    myDiv2.appendChild(myP);
    var myList = document.createElement("select");
    myP.appendChild(myList);                     /* note myP is pRr */
    myList.setAttribute("id", "selRr");
    myList.setAttribute("name", "selRr");
    var tmpValue;
    for (var i = 1; i <= 23; i++) {
         if (i < 14) {
            tmpValue = i + 3
        } else {
            tmpValue = i * 2 - 10
        }
        var myOption = document.createElement("option");
        myOption.innerHTML = tmpValue;
        myOption.setAttribute("value", parseFloat(tmpValue));
        myList.appendChild(myOption)
    }
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "resprate";
    myLabel.appendChild(document.createTextNode("BPM"));
    myP.appendChild(myLabel);                     /* note myP is pRr */
	
    var myP = document.createElement("p");
    myP.innerHTML = "PEEP:";
    myDiv2.appendChild(myP);
    var myList = document.createElement("select");
    myList.setAttribute("id", "selPeep");
    myList.setAttribute("name", "selPeep");
    myP.appendChild(myList);                      /* note myP is pPeep */
    var tmpValue;
    for (var i = 0; i <= 6; i++) {
        tmpValue = i * 2.5;
        var myOption = document.createElement("option");
        myOption.innerHTML = tmpValue;
        myOption.setAttribute("value", parseFloat(tmpValue));
        myList.appendChild(myOption)
    }
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "peep";
    myLabel.appendChild(document.createTextNode("cm H2O"));
    myP.setAttribute("id", "pPeep");
    myP.appendChild(myLabel);                     /* note myP is pPeep */
	
    var myDiv3 = document.createElement("div");
    myDiv3.setAttribute("id", "divBreathing3");
    $("divDisplayContent").appendChild(myDiv3);
    var myP = document.createElement("p");
    myP.innerHTML = "Circle System";
    myP.setAttribute("id", "pCircleSystem");
    myDiv3.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnCheckCircuit");
    myButton.innerHTML = "Check Circuit";
    myDiv3.appendChild(myButton);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pCircleStatus");
    myP.innerHTML = "Circuit is intact. Valves are moving normally. CO2 absorbant is fresh.";
    myDiv3.appendChild(myP);
	
    if (UserAirwayStr == "none") {
		$("rbBagControl").disabled = true;
        $("labelBagControl").style.color = "var(--text-secondary)";
		$("rbVentilator").disabled = true;
		$("labelVentilator").style.color = "var(--text-secondary)";
		$("pVentSettings").hide();
		$("pTv").hide();
		$("pRr").hide();
		$("pPeep").hide();
    } else {
       $("pVentSettings").innerHTML = "";
            $("rbBagControl").disabled = false;
       $("labelBagControl").style.color = "var(--text-primary)";
            $("rbVentilator").disabled = false;
       $("labelVentilator").style.color = "var(--text-primary)"; 
       $("pVentSettings").show();
    }
	
    if (UserBreathModeStr == "spontaneous") {
        $("rbSpontaneous").checked = true;
        $("rbBagControl").checked = false;
        $("rbVentilator").checked = false;
        $("pVentSettings").hide();
        $("pTv").hide();
        $("pRr").hide();
        $("pPeep").hide();

    } else if (UserBreathModeStr == "bagControl") {
        $("pVentSettings").innerHTML = "Bag Assist/Control Settings";
        $("rbSpontaneous").checked = false;
        $("rbBagControl").checked = true;
        $("rbVentilator").checked = false;
        $("selTv").value = UserBagTv;
        $("pTv").style.color = "var(--text-primary)";
            $("selTv").classList.remove('disabled');
            $("selTv").style.pointerEvents = 'auto';
        $("selRr").value = UserBagRr;
        $("pRr").style.color = "var(--text-primary)";
            $("selRr").classList.remove('disabled');
            $("selRr").style.pointerEvents = 'auto';
        $("selPeep").value = UserPeep;
        $("pPeep").style.color = "var(--text-primary)";
            $("selPeep").classList.remove('disabled');
            $("selPeep").style.pointerEvents = 'auto';
       $("pVentSettings").show();
       $("pTv").show();
       $("pRr").show();
       $("pPeep").show();
    } else if (UserBreathModeStr == "ventilator") {
        $("pVentSettings").innerHTML = "Ventilator Settings";
        $("rbSpontaneous").checked = false;
        $("rbBagControl").checked = false;
        $("rbVentilator").checked = true;
        $("selTv").value = UserVentTv;
        $("pTv").style.color = "var(--text-primary)";
            $("selTv").classList.remove('disabled');
            $("selTv").style.pointerEvents = 'auto';
        $("selRr").value = UserVentRr;
        $("pRr").style.color = "var(--text-primary)";
            $("selRr").classList.remove('disabled');
            $("selRr").style.pointerEvents = 'auto';
        $("selPeep").value = UserPeep;
        $("pPeep").style.color = "var(--text-primary)";
            $("selPeep").classList.remove('disabled');
            $("selPeep").style.pointerEvents = 'auto';
       $("pVentSettings").show();
       $("pTv").show();
       $("pRr").show();
       $("pPeep").show();
    }
    $("pCircleStatus").hide();
    $("rbSpontaneous").observe("click", SetBreathMode);
    $("rbBagControl").observe("click", SetBreathMode);
    $("rbVentilator").observe("click", SetBreathMode);
    $("selTv").observe("change", SetBagAndVent);
    $("selRr").observe("change", SetBagAndVent);
    $("selPeep").observe("change", SetBagAndVent)
    $("btnCheckCircuit").observe("click", ClickBtnCheckCircuit);
}

function SetBreathMode() {
    if ($("rbBagControl").checked) {
        UserBreathModeStr = "bagControl";
        $("pVentSettings").innerHTML = "Bag Assist/Control Settings";
        $("pVentSettings").show();
        $("pTv").show();
        $("pRr").show();
        $("pPeep").show();
        $("selTv").value = UserBagTv;
        $("pTv").style.color = "var(--text-primary)";
            $("selTv").classList.remove('disabled');
            $("selTv").style.pointerEvents = 'auto';
        $("selRr").value = UserBagRr;
        $("pRr").style.color = "var(--text-primary)";
            $("selRr").classList.remove('disabled');
            $("selRr").style.pointerEvents = 'auto';
        $("selPeep").value = UserPeep;
        $("pPeep").style.color = "var(--text-primary)";
            $("selPeep").classList.remove('disabled');
            $("selPeep").style.pointerEvents = 'auto';
    } else if ($("rbVentilator").checked) {
        UserBreathModeStr = "ventilator";
        $("pVentSettings").innerHTML = "Ventilator Settings";
        $("pVentSettings").show();
        $("pTv").show();
        $("pRr").show();
        $("pPeep").show();
       $("selTv").value = UserVentTv;
        $("pTv").style.color = "var(--text-primary)";
            $("selTv").classList.remove('disabled');
            $("selTv").style.pointerEvents = 'auto';
        $("selRr").value = UserVentRr;
        $("pRr").style.color = "var(--text-primary)";
            $("selRr").classList.remove('disabled');
            $("selRr").style.pointerEvents = 'auto';
       $("selPeep").value = UserPeep;
        $("pPeep").style.color = "var(--text-primary)";
            $("selPeep").classList.remove('disabled');
            $("selPeep").style.pointerEvents = 'auto';
    } else {
        UserBreathModeStr = "spontaneous";
        $("pVentSettings").innerHTML = "";
        $("pVentSettings").hide();
        $("pTv").hide();
        $("pRr").hide();
        $("pPeep").hide();
        CaseLogStr2 = CaseLogStr2.concat("Ventilation set to spontaneous breathing.\n")
    }
    SetBagAndVent()
}

function SetBagAndVent() {
    if ($("rbBagControl").checked) {
        UserBagTv = parseFloat($("selTv").value);
        UserBagRr = parseFloat($("selRr").value);
        UserPeep = parseFloat($("selPeep").value);
        CaseLogStr2 = CaseLogStr2.concat("Bag/Control TV: " + UserBagTv + " cc, RR: " + UserBagRr + " bpm, PEEP: " + UserPeep + " cm H2O\n")
    } else if ($("rbVentilator").checked) {
        UserVentTv = parseFloat($("selTv").value);
        UserVentRr = parseFloat($("selRr").value);
        UserPeep = parseFloat($("selPeep").value);
        CaseLogStr2 = CaseLogStr2.concat("Ventilator TV: " + UserVentTv + " cc, RR: " + UserVentRr + " bpm, PEEP: " + UserPeep + " cm H2O\n")
    }
}

function ClickBtnCheckCircuit() {
    $("pCircleStatus").show();
    UserCheckedCircuitFlag = true
}

function ShowDrugsScreen() {
	UserShowingCenter = "drugs"; 
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
	
    var myDiv1 = document.createElement("div");
    myDiv1.setAttribute("id", "divDrugs1");
    $("divDisplayContent").appendChild(myDiv1);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pDrugAdmin");
    myP.innerHTML = "Drug Administration";
    myDiv1.appendChild(myP);
    var myList = document.createElement("select");
    myList.setAttribute("id", "selDrugList");
    for (var i = 0; i < DrugInfo.Drugs.length; i++) {
        var myOption = document.createElement("option");
        myOption.setAttribute("value", i);
        myOption.innerHTML = DrugInfo.Drugs[i].nameStr;
        myList.appendChild(myOption)
    }
    myDiv1.appendChild(myList);
    var mySpan = document.createElement("span");
    mySpan.setAttribute("id", "spanDrugBolus");
    myDiv1.appendChild(mySpan);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pDrugBolus");
    myP.innerHTML = "Bolus:";
    mySpan.appendChild(myP);
    var myList = document.createElement("select");
    myList.setAttribute("id", "selDrugBolus");
    myList.setAttribute("name", "selDrugBolus");
    mySpan.appendChild(myList);
    var myOption = document.createElement("option");
    myOption.innerHTML = 0;
    myOption.setAttribute("value", 0);
    myList.appendChild(myOption);
    var myLabel = document.createElement("label");
    myLabel.setAttribute("id", "lblBolusUnits");
    myLabel.htmlFor = "selDrugBolus";
    myLabel.appendChild(document.createTextNode("none"));
    mySpan.appendChild(myLabel);
    mySpan.hide();
    var myBr = document.createElement("br");
    myDiv1.appendChild(myBr);
	
    var mySpan = document.createElement("span");
    mySpan.setAttribute("id", "spanDrugInfusion");
    myDiv1.appendChild(mySpan);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pDrugInfusion");
    myP.innerHTML = "Infusion:";
    mySpan.appendChild(myP);
    var myList = document.createElement("select");
    myList.setAttribute("id", "selDrugInfusion");
    myList.setAttribute("name", "selDrugInfusion");
    mySpan.appendChild(myList);
    var myOption = document.createElement("option");
    myOption.innerHTML = 0;
    myOption.setAttribute("value", 0);
    myList.appendChild(myOption);
    var myLabel = document.createElement("label");
    myLabel.setAttribute("id", "lblInfusionUnits");
    myLabel.htmlFor = "selDrugInfusion";
    myLabel.appendChild(document.createTextNode("none"));
    mySpan.appendChild(myLabel);
    mySpan.hide();
	
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnDrugAdminister");
    myButton.innerHTML = "Administer";
    myDiv1.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnDrugCancel");
    myButton.innerHTML = "Cancel";
    myDiv1.appendChild(myButton);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pDrugConfirmation");
    myDiv1.appendChild(myP);
	
    var myDiv2 = document.createElement("div");
    myDiv2.setAttribute("id", "divDrugs2");
    $("divDisplayContent").appendChild(myDiv2);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pDrugInfo");
    myP.innerHTML = "Drug Information";
    myDiv2.appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnDrugInfo");
    myButton.innerHTML = "Display Drug Info";
    myDiv2.appendChild(myButton);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pDrugInfoText");
    myDiv2.appendChild(myP);

    var myDiv3 = document.createElement("div");
    myDiv3.setAttribute("id", "divDrugs3");
    $("divDisplayContent").appendChild(myDiv3);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pDrugInfusions");
    myP.innerHTML = "Current Infusions";
    myDiv3.appendChild(myP);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pInfusionList");
    myP.innerHTML = "Current Infusions";
    myDiv3.appendChild(myP);

    $("btnDrugAdminister").hide();
    $("btnDrugCancel").hide();
    $("pDrugConfirmation").hide();
    $("pDrugInfo").hide();
    $("btnDrugInfo").hide();
    $("pDrugInfoText").hide();
	
	if (CurrentCase.helpFlag == false ) {
		$("pDrugInfo").hide();
		$("btnDrugInfo").hide();
	}
	
    $("selDrugList").observe("change", ChangeDrugSelection);
    $("selDrugInfusion").observe("change", ChangeDrugInfusion);
    $("selDrugBolus").observe("change", ChangeDrugBolus);
    $("btnDrugAdminister").observe("click", ClickBtnDrugAdminister);
    $("btnDrugCancel").observe("click", ClickBtnDrugCancel);
    $("btnDrugInfo").observe("click", ClickBtnDrugInfo);
    UserDrugIndex = 0;
	DisplayInfusions();
}

function ChangeDrugSelection() {
    $("pDrugConfirmation").hide();
    UserDrugIndex = $("selDrugList").value;
	
    if (UserDrugIndex > 0) {
		if ((DrugInfo.Drugs[UserDrugIndex].nameStr == "Desflurane") || 
		    (DrugInfo.Drugs[UserDrugIndex].nameStr == "Halothane") ||
		    (DrugInfo.Drugs[UserDrugIndex].nameStr == "Isoflurane") ||
		    (DrugInfo.Drugs[UserDrugIndex].nameStr == "Sevoflurane")) {
			$("pDrugInfusion").innerHTML = "Amount:";
			if (DrugInfo.Drugs[UserDrugIndex].nameStr == UserVaporizerStr) {
				DrugInfo.Drugs[UserDrugIndex].adminInfusionRate = UserVaporizerAmount;
				$("selVapAmount").value = UserVaporizerAmount; 
			} else {
				DrugInfo.Drugs[UserDrugIndex].adminInfusionRate = 0.0;
			}

		} else {  // IV drug
			$("pDrugInfusion").innerHTML = "Infusion:";

		}

			var tmpValue;
			if (DrugInfo.Drugs[UserDrugIndex].bolusUnit != "none") {
				$("selDrugBolus").length = 0;
				for (var i = 0; i <= DrugInfo.Drugs[UserDrugIndex].bolusDoses.length - 1; i++) {
					var myOption = document.createElement("option");
					tmpValue = DrugInfo.Drugs[UserDrugIndex].bolusDoses[i]; 
					myOption.innerHTML = tmpValue;
					myOption.setAttribute("value", tmpValue);
					$("selDrugBolus").appendChild(myOption)
				}
				$("lblBolusUnits").innerHTML = DrugInfo.Drugs[UserDrugIndex].bolusUnit;
				$("spanDrugBolus").show();
			} else {
				$("spanDrugBolus").hide();
			}
			if (DrugInfo.Drugs[UserDrugIndex].infusionUnit != "none") {
				$("selDrugInfusion").length = 0;
				for (var i = 0; i <= DrugInfo.Drugs[UserDrugIndex].infusionDoses.length - 1; i++) {
					var myOption = document.createElement("option");
					myOption.innerHTML = DrugInfo.Drugs[UserDrugIndex].infusionDoses[i];
					myOption.setAttribute("value", DrugInfo.Drugs[UserDrugIndex].infusionDoses[i]);
					$("selDrugInfusion").appendChild(myOption)
				}
				$("lblInfusionUnits").innerHTML = DrugInfo.Drugs[UserDrugIndex].infusionUnit;
				$("spanDrugInfusion").show()
			} else {
				$("spanDrugInfusion").hide()
			}

			$("selDrugBolus").value = 0;
			$("selDrugInfusion").value = DrugInfo.Drugs[UserDrugIndex].adminInfusionRate;
			$("btnDrugAdminister").hide();
			$("btnDrugCancel").hide();
	
			if (CurrentCase.helpFlag == true ) {
				$("pDrugInfo").show();
				$("btnDrugInfo").show();
			} else {
				$("pDrugInfo").hide();
				$("btnDrugInfo").hide();
			}
			
			$("pDrugInfoText").hide();
    }
}

function ChangeDrugBolus() {
	$("btnDrugAdminister").show();
	$("btnDrugCancel").show();
    $("pDrugConfirmation").hide();
	DisableSideMenu();
}

function ChangeDrugInfusion() {
	$("btnDrugAdminister").show();
	$("btnDrugCancel").show();
    $("pDrugConfirmation").hide();
	DisableSideMenu();
}

function ClickBtnDrugAdminister() {
	var recordFlag = true;
    var bAmount;
    var iAmount;
    bAmount = $("selDrugBolus").value;
    $("selDrugBolus").value = 0;
    iAmount = $("selDrugInfusion").value;
    $("pDrugConfirmation").innerHTML = "Administered!";
    if (bAmount > 0) {
        DrugInfo.Drugs[UserDrugIndex].adminBolusAmount = parseFloat(bAmount);
        DrugInfo.Drugs[UserDrugIndex].adminBolusLevel += DrugInfo.Drugs[UserDrugIndex].adminBolusAmount;
        DrugInfo.Drugs[UserDrugIndex].adminBolusFlag = true;
        DrugInfo.Drugs[UserDrugIndex].adminBolusTime = CaseTimeInSec;
        DrugInfo.Drugs[UserDrugIndex].true;
        if (DrugInfo.Drugs[UserDrugIndex].nameStr == "Sodium Bicarb") {
            PddAddedBicarb += 5 * DrugInfo.Drugs[UserDrugIndex].adminBolusAmount / CurrentCase.leanBodyMass
        }
    }
    DrugInfo.Drugs[UserDrugIndex].adminInfusionRate = parseFloat(iAmount);
	
	if ((DrugInfo.Drugs[UserDrugIndex].nameStr == "Desflurane") || 
		(DrugInfo.Drugs[UserDrugIndex].nameStr == "Halothane") ||
		(DrugInfo.Drugs[UserDrugIndex].nameStr == "Isoflurane") ||
		(DrugInfo.Drugs[UserDrugIndex].nameStr == "Sevoflurane")) {
		// inhalation agent
		DrugInfo.Drugs[UserDrugIndex].adminInfusionFlag = false;
		if (DrugInfo.Drugs[UserDrugIndex].nameStr == UserVaporizerStr) {
            $("selVapAmount").value = iAmount;
			UserVaporizerAmount = iAmount;
			DrugInfo.Drugs[UserDrugIndex].adminInfusionAmount = iAmount;
			var tmpStr = DrugInfo.Drugs[UserDrugIndex].nameStr + " set to " + iAmount + " %\n";
			$("pDrugConfirmation").innerHTML = tmpStr;
			CaseLogStr2 = CaseLogStr2.concat(tmpStr);
			recordFlag = false;
		} else {
			$("pDrugConfirmation").innerHTML = "Change vaporizer";
			recordFlag = false;
		}

	} else if (iAmount > 0){  
		// IV drug
		DrugInfo.Drugs[UserDrugIndex].adminInfusionFlag = true;
		$("pDrugConfirmation").innerHTML = "Administered!";
	}

	if (recordFlag == true) {
		RecordMeds(bAmount, iAmount);
	}
    $("pDrugConfirmation").show();
	$("btnDrugAdminister").hide();
	$("btnDrugCancel").hide();
	DisplayInfusions()
	EnableSideMenu();
}

function ClickBtnDrugCancel() {
	$("btnDrugAdminister").hide();
	$("btnDrugCancel").hide();
	$("selDrugBolus").value = 0;	
	$("selDrugInfusion").value = DrugInfo.Drugs[UserDrugIndex].adminInfusionRate;	
    $("pDrugConfirmation").innerHTML = "Drug order canceled.";
    $("pDrugConfirmation").show();
	EnableSideMenu();
}


function ClickBtnDrugInfo() {
    $("btnDrugInfo").hide();
    $("pDrugInfoText").innerText = DrugInfo.Drugs[$("selDrugList").value].actionStr +  
		"\n\nUse: " + "\n" + DrugInfo.Drugs[$("selDrugList").value].useStr + 
		"\n\nDose: " + "\n" + DrugInfo.Drugs[$("selDrugList").value].doseStr + 
		"\n\nAdverse effects: " + "\n" + DrugInfo.Drugs[$("selDrugList").value].complicationStr; 
    $("pDrugInfoText").show();
}


function DisplayInfusions() {
	var myStr;
    myStr = "";
    for (var iDrug = 1; iDrug < DrugInfo.Drugs.length; iDrug++) {
		// was     if (DrugInfo.Drugs[iDrug].adminInfusionRate > 0) {
        if (DrugInfo.Drugs[iDrug].adminInfusionFlag == true) {
            myStr = myStr + DrugInfo.Drugs[iDrug].nameStr + " " + DrugInfo.Drugs[iDrug].adminInfusionRate + " " + DrugInfo.Drugs[iDrug].infusionUnit + "\n"
        }
    }
    if (myStr == "") {
        myStr = "At this time there are no infusions running."
    }

    $("pInfusionList").innerText = myStr; 
    $("pInfusionList").show();
}

function ShowFluidsScreen() {
	UserShowingCenter = "fluids"; 
	UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divFluids1");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "IV #1";
    myP.setAttribute("id", "pTitle1");
    $("divFluids1").appendChild(myP);
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selIvFluid1");
    mySelect.setAttribute("name", "selIvFluid1");
    myP.appendChild(mySelect);
    for (var i = 0; i < IvFluidStr.length; i++) {
        var myOption = document.createElement("option");
        myOption.innerHTML = IvFluidStr[i];
        myOption.setAttribute("value", IvFluidStr[i]);
        mySelect.appendChild(myOption)
    }
    var myP = document.createElement("p");
    myP.innerHTML = "Infusion Rate: ";
    myP.setAttribute("id", "pIvRate1");
    myP.setAttribute("name", "pIvRate1");
    $("divFluids1").appendChild(myP);
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selIvRate1");
    mySelect.setAttribute("name", "selIvRate1");
    myP.appendChild(mySelect);
    var tmpPedsScaler;
    if (CurrentCase.leanBodyMass > 19) {
        tmpPedsScaler = 1
    } else {
        tmpPedsScaler = 10
    }
    for (var i = 0; i < 20; i++) {
        var myOption = document.createElement("option");
        var tmpValue;
        if (i < 11) {
            tmpValue = (i * 50) / tmpPedsScaler
        } else if (i < 16) {
            tmpValue = ((i - 5) * 100) / tmpPedsScaler
        } else {
            tmpValue = ((i - 14) * 1000) / tmpPedsScaler
        }
        myOption.innerHTML = tmpValue;
        myOption.setAttribute("value", parseFloat(tmpValue));
        mySelect.appendChild(myOption)
    }
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "selIvRate1";
    myLabel.appendChild(document.createTextNode("mL/hr")); 
    myLabel.setAttribute("id", "lblIvRate1");
    myP.appendChild(myLabel);
    var myP = document.createElement("p");
    myP.innerHTML = "Bolus Amount:";
    myP.setAttribute("id", "pIvBolus1");
    myP.setAttribute("name", "pIvBolus1");
    $("divFluids1").appendChild(myP);
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selIvBolus1");
    mySelect.setAttribute("name", "selIvBolus1");
    myP.appendChild(mySelect);
    for (var i = 0; i < 10; i++) {
        var myOption = document.createElement("option");
        var tmpValue;
        if (i < 6) {
            tmpValue = (i * 50) / tmpPedsScaler
        } else if (i < 9) {
            tmpValue = ((i - 3) * 100) / tmpPedsScaler
        } else {
            tmpValue = 1000 / tmpPedsScaler
        }
        myOption.innerHTML = tmpValue;
        myOption.setAttribute("value", parseFloat(tmpValue));
        mySelect.appendChild(myOption)
    }
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "selIvBolus1";
    myLabel.appendChild(document.createTextNode("mL"));
    myLabel.setAttribute("id", "lblIvRate1");
    myP.appendChild(myLabel);
 
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divFluids2");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "IV #2";
    myP.setAttribute("id", "pTitle2");
    $("divFluids2").appendChild(myP);
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selIvFluid2");
    mySelect.setAttribute("name", "selIvFluid2");
    myP.appendChild(mySelect);
    for (var i = 0; i < IvFluidStr.length; i++) {
        var myOption = document.createElement("option");
        myOption.innerHTML = IvFluidStr[i];
        myOption.setAttribute("value", IvFluidStr[i]);
        mySelect.appendChild(myOption)
    }
    var myP = document.createElement("p");
    myP.innerHTML = "Infusion Rate: ";
    myP.setAttribute("id", "pIvRate2");
    myP.setAttribute("name", "pIvRate2");
    $("divFluids2").appendChild(myP);
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selIvRate2");
    mySelect.setAttribute("name", "selIvRate2");
    myP.appendChild(mySelect);
    for (var i = 0; i < 20; i++) {
        var myOption = document.createElement("option");
        var tmpValue;
        if (i < 11) {
            tmpValue = (i * 50) / tmpPedsScaler
        } else if (i < 16) {
            tmpValue = ((i - 5) * 100) / tmpPedsScaler
        } else {
            tmpValue = ((i - 14) * 1000) / tmpPedsScaler
        }
        myOption.innerHTML = tmpValue;
        myOption.setAttribute("value", parseFloat(tmpValue));
        mySelect.appendChild(myOption)
    }
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "selIvRate2";
    myLabel.appendChild(document.createTextNode("mL/hr"));
    myLabel.setAttribute("id", "lblIvRate2");
    myP.appendChild(myLabel);
    var myP = document.createElement("p");
    myP.innerHTML = "Bolus Amount:";
    myP.setAttribute("id", "pIvBolus2");
    myP.setAttribute("name", "pIvBolus2");
    $("divFluids2").appendChild(myP);
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selIvBolus2");
    mySelect.setAttribute("name", "selIvBolus2");
    myP.appendChild(mySelect);
    for (var i = 0; i < 10; i++) {
        var myOption = document.createElement("option");
        var tmpValue;
        if (i < 6) {
            tmpValue = (i * 50) / tmpPedsScaler
        } else if (i < 9) {
            tmpValue = ((i - 3) * 100) / tmpPedsScaler
        } else {
            tmpValue = 1000 / tmpPedsScaler
        }
        myOption.innerHTML = tmpValue;
        myOption.setAttribute("value", parseFloat(tmpValue));
        mySelect.appendChild(myOption)
    }
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "selIvBolus2";
    myLabel.setAttribute("id", "lblIvRate1");
    myLabel.appendChild(document.createTextNode("mL"));
    myP.appendChild(myLabel);

    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divFluids3");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "Fluid Status";
    myP.setAttribute("id", "pTitle3");
    $("divFluids3").appendChild(myP);
    var myPlr = document.createElement("p");
    myPlr.innerHTML = "LR administered: " + parseInt(PddTlr) + " mL";
    myPlr.setAttribute("id", "pLr");
    $("divFluids3").appendChild(myPlr);
    var myPns = document.createElement("p");
    myPns.innerHTML = "NS administered: " + parseInt(PddTns) + " mL";
    myPns.setAttribute("id", "pNs");
    $("divFluids3").appendChild(myPns);
    var myPalb = document.createElement("p");
    myPalb.innerHTML = "Albumin administered: " + parseInt(PddTalb) + " mL";
    myPalb.setAttribute("id", "pAlb");
    $("divFluids3").appendChild(myPalb);
    var myPprbc = document.createElement("p");
    myPprbc.innerHTML = "PRBC administered: " + parseInt(PddTprbc) + " mL";
    myPprbc.setAttribute("id", "pPrbc");
    $("divFluids3").appendChild(myPprbc);
    var myPuo = document.createElement("p");
    myPuo.innerHTML = "Urine output: " + parseInt(PddTuo) + " mL";
    myPuo.setAttribute("id", "pUo");
    $("divFluids3").appendChild(myPuo);
    var myPebl = document.createElement("p");
    myPebl.innerHTML = "Blood loss: " + parseInt(PddTebl) + " mL";
    myPebl.setAttribute("id", "pEbl");
    $("divFluids3").appendChild(myPebl);
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divFluids4");
    $("divDisplayContent").appendChild(myDiv);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnIvConfirm");
    myButton.innerHTML = "Confirm";
    myButton.hide();
    $("divFluids4").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnIvCancel");
    myButton.innerHTML = "Cancel";
    myButton.hide();
    $("divFluids4").appendChild(myButton);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pFluidConfirmation");
	myP.hide();
    $("divFluids4").appendChild(myP);

    $("selIvFluid1").value = IvAdmin.Iv[0].fluidStr;
    $("selIvRate1").value = IvAdmin.Iv[0].infusionRate;
    if (IvAdmin.Iv[0].fluidStr == "None") {
        $("pIvRate1").hide();
        $("pIvBolus1").hide();
    } else {
        $("pIvRate1").show();
        $("pIvBolus1").show();
    }
	
    $("selIvFluid2").value = IvAdmin.Iv[1].fluidStr;
    $("selIvRate2").value = IvAdmin.Iv[1].infusionRate;
    if (IvAdmin.Iv[1].fluidStr == "None") {
        $("pIvRate2").hide();
        $("pIvBolus2").hide()
    } else {
        $("pIvRate2").show();
        $("pIvBolus2").show();
    }

    $("selIvFluid1").observe("change", ChangeIvFluid1);
    $("selIvFluid2").observe("change", ChangeIvFluid2);
    $("selIvRate1").observe("change", ChangeIvAmount);
    $("selIvBolus1").observe("change", ChangeIvAmount);
    $("selIvRate2").observe("change", ChangeIvAmount);
    $("selIvBolus2").observe("change", ChangeIvAmount);
    $("btnIvConfirm").observe("click", ClickBtnIvConfirm);
    $("btnIvCancel").observe("click", ClickBtnIvCancel);
}

function ChangeIvAmount() {
            $("btnIvConfirm").classList.remove('disabled');
            $("btnIvConfirm").style.pointerEvents = 'auto';
    $("btnIvConfirm").show()
            $("btnIvCancel").classList.remove('disabled');
            $("btnIvCancel").style.pointerEvents = 'auto';
    $("btnIvCancel").show();
    $("pFluidConfirmation").hide();
	DisableSideMenu();
}

function ChangeIvFluid1() {
    if ($("selIvFluid1").value == "None") {
        $("pIvRate1").hide();
        $("pIvBolus1").hide();
        $("pFluidConfirmation").hide();    
    } else {
        $("pIvRate1").show();
        $("pIvBolus1").show(); 
    }
            $("btnIvConfirm").classList.remove('disabled');
            $("btnIvConfirm").style.pointerEvents = 'auto';
    $("btnIvConfirm").show()
            $("btnIvCancel").classList.remove('disabled');
            $("btnIvCancel").style.pointerEvents = 'auto';
    $("btnIvCancel").show();
    $("pFluidConfirmation").hide();
	DisableSideMenu();
}

function ChangeIvFluid2() {
    if ($("selIvFluid2").value == "None") {
        $("pIvRate2").hide();
        $("pIvBolus2").hide()
    } else {
        $("pIvRate2").show();
        $("pIvBolus2").show();
    }
            $("btnIvConfirm").classList.remove('disabled');
            $("btnIvConfirm").style.pointerEvents = 'auto';
    $("btnIvConfirm").show()
            $("btnIvCancel").classList.remove('disabled');
            $("btnIvCancel").style.pointerEvents = 'auto';
    $("btnIvCancel").show();
    $("pFluidConfirmation").hide();
	DisableSideMenu();
}

function ClickBtnIvConfirm() {
    IvAdmin.Iv[0].fluidStr = $("selIvFluid1").value;
    IvAdmin.Iv[1].fluidStr = $("selIvFluid2").value;
    IvAdmin.Iv[0].infusionRate = parseFloat($("selIvRate1").value);
    IvAdmin.Iv[0].bolusAmount = parseFloat($("selIvBolus1").value);
    IvAdmin.Iv[1].infusionRate = parseFloat($("selIvRate2").value);
    IvAdmin.Iv[1].bolusAmount = parseFloat($("selIvBolus2").value);
    RecordFluids();
    for (var i = 0; i <= 1; i++) {
        if (IvAdmin.Iv[i].fluidStr == IvFluidStr[1]) {
            PddTlr += IvAdmin.Iv[i].bolusAmount;
        } else if (IvAdmin.Iv[i].fluidStr == IvFluidStr[2]) {
            PddTns += IvAdmin.Iv[i].bolusAmount;
        } else if (IvAdmin.Iv[i].fluidStr == IvFluidStr[3]) {
            PddTalb += IvAdmin.Iv[i].bolusAmount;
        } else if (IvAdmin.Iv[i].fluidStr == IvFluidStr[4]) {
            PddTprbc += IvAdmin.Iv[i].bolusAmount;
        }
        IvAdmin.Iv[i].bolusAmount = 0
    }
    $("selIvBolus1").value = 0;
    $("selIvBolus2").value = 0;
    $("pLr").innerHTML = "LR administered: " + parseInt(PddTlr) + " mL";
    $("pNs").innerHTML = "NS administered: " + parseInt(PddTns) + " mL";
    $("pAlb").innerHTML = "Albumin administered: " + parseInt(PddTalb) + " mL";
    $("pPrbc").innerHTML = "PRBC administered: " + parseInt(PddTprbc) + " mL";
    $("pUo").innerHTML = "Urine output: " + parseInt(PddTuo) + " mL";
    $("pEbl").innerHTML = "Blood loss: " + parseInt(PddTebl) + " mL";
    $("btnIvConfirm").hide();
    $("btnIvCancel").hide();
    $("pFluidConfirmation").innerHTML = "New fluid order confirmed";
    $("pFluidConfirmation").show();
	EnableSideMenu();
}

function ClickBtnIvCancel() {
    $("btnIvConfirm").hide();
    $("btnIvCancel").hide();
    $("pFluidConfirmation").innerHTML = "New fluid order canceled";
    $("pFluidConfirmation").show();
	EnableSideMenu();
}

function ShowLabsScreen() {
	UserShowingCenter = "labs"; 
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divLabs1");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "Laboratory Studies";
    myP.setAttribute("id", "pLabStudies");
    $("divLabs1").appendChild(myP);
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbAbg");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbAbg";
    myLabel.appendChild(document.createTextNode("Arterial Blood Gas"));
    myDiv.appendChild(myCheckbox);
    myDiv.appendChild(myLabel);
    var myBr = document.createElement("br"); 
    myDiv.appendChild(myBr);  
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbHct");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbHct";
    myLabel.appendChild(document.createTextNode("Hematocrit"));
    myDiv.appendChild(myCheckbox);
    myDiv.appendChild(myLabel);
    var myBr = document.createElement("br"); 
    myDiv.appendChild(myBr); 
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbLytes");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbLytes";
    myLabel.appendChild(document.createTextNode("Electrolytes"));
    myDiv.appendChild(myCheckbox);
    myDiv.appendChild(myLabel);
    var myBr = document.createElement("br");  
    myDiv.appendChild(myBr);  
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbGluc");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbGluc";
    myLabel.appendChild(document.createTextNode("Blood glucose"));
    myDiv.appendChild(myCheckbox);
    myDiv.appendChild(myLabel);
    var myBr = document.createElement("br"); 
    myDiv.appendChild(myBr); 
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnOrderLabs");
    myButton.innerHTML = "Order Labs";
    $("divLabs1").appendChild(myButton);

    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divLabs2");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "Laboratory Results";
    myP.setAttribute("id", "pLabResults");
    $("divLabs2").appendChild(myP);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pLabTime");
    $("divLabs2").appendChild(myP);
    $("pLabTime").hide();
    var myPabg = document.createElement("p");
    myPabg.innerHTML = "ABG: pH: " + PrpArtPh.toFixed(2) + ",  Pco2: " + parseInt(PrpArtPco2) + ",  Po2:  " + parseInt(PrpArtPo2) + ",  HCO3: " + PrpArtBicarb.toFixed(1);
    myPabg.setAttribute("id", "pAbg");
    $("divLabs2").appendChild(myPabg);
    $("pAbg").hide();
    var myPhct = document.createElement("p");
    myPhct.innerHTML = "Hematocrit: " + parseInt(CurrentState.hct);
    myPhct.setAttribute("id", "pHct");
    $("divLabs2").appendChild(myPhct);
    $("pHct").hide();
    var myPlytes = document.createElement("p");
    myPlytes.innerHTML = "Na: " + parseInt(CurrentState.sodium) + ",  K: " + PrpPotassium.toFixed(1);
    myPlytes.setAttribute("id", "pLytes");
    $("divLabs2").appendChild(myPlytes);
    $("pLytes").hide();
    var myPgluc = document.createElement("p");
    myPgluc.innerHTML = "Blood glucose: " + parseInt(CurrentState.glucose);
    myPgluc.setAttribute("id", "pGluc");
    $("divLabs2").appendChild(myPgluc);
    $("pGluc").hide()

    $("cbAbg").observe("click", ClickLabsCheckbox);
    $("cbHct").observe("click", ClickLabsCheckbox);
    $("cbLytes").observe("click", ClickLabsCheckbox);
    $("cbGluc").observe("click", ClickLabsCheckbox);
    $("btnOrderLabs").observe("click", ClickBtnOrderLabs);
}



function ClickLabsCheckbox() {
    if ($("cbAbg").checked || $("cbHct").checked || $("cbLytes").checked || $("cbGluc").checked) {
            $("btnOrderLabs").classList.remove('disabled');
            $("btnOrderLabs").style.pointerEvents = 'auto';
    } else {
            $("btnOrderLabs").classList.add('disabled');
            $("btnOrderLabs").style.pointerEvents = 'none';
    }
}

function ClickBtnOrderLabs() {
    $("pLabTime").innerHTML = "At " + MakeTimeStr() + " :";
    $("pLabTime").show();
    $("pAbg").innerHTML = "";
    $("pHct").innerHTML = "";
    $("pLytes").innerHTML = "";
    $("pGluc").innerHTML = "";
    if ($("cbAbg").checked) {
        var tmpStr;
        tmpStr = "ABG: pH: " + PrpArtPh.toFixed(2) + ",  Pco2: " + parseInt(PrpArtPco2) + ",  Po2:  " + parseInt(PrpArtPo2) + ",  HCO3: " + PrpArtBicarb.toFixed(1);
        $("pAbg").innerHTML = "" + tmpStr;
        $("pAbg").show();
        CaseLogStr2 = CaseLogStr2.concat(tmpStr + "\n")
    }
    if ($("cbHct").checked) {
        var tmpStr;
        tmpStr = "Hematocrit: " + parseInt(CurrentState.hct);
        $("pHct").innerHTML = "" + tmpStr;
        $("pHct").show();
        CaseLogStr2 = CaseLogStr2.concat(tmpStr + "\n")
    }
    if ($("cbLytes").checked) {
        var tmpStr;
        tmpStr = "Na: " + parseInt(CurrentState.sodium) + ",  K: " + PrpPotassium.toFixed(1);
        $("pLytes").innerHTML = "" + tmpStr;
        $("pLytes").show();
        CaseLogStr2 = CaseLogStr2.concat(tmpStr + "\n")
    }
    if ($("cbGluc").checked) {
        var tmpStr;
        tmpStr = "Blood glucose: " + parseInt(CurrentState.glucose);
        $("pGluc").innerHTML = "" + tmpStr;
        $("pGluc").show();
        CaseLogStr2 = CaseLogStr2.concat(tmpStr + "\n")
    }
    $("cbAbg").checked = false;
    $("cbHct").checked = false;
    $("cbLytes").checked = false;
    $("cbGluc").checked = false;
            $("btnOrderLabs").classList.add('disabled');
            $("btnOrderLabs").style.pointerEvents = 'none';
}

function ShowSurgeonScreen() {
	UserShowingCenter = "surgeon"; 
	UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divSurgeon1");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "Surgeon:";
    myP.setAttribute("id", "pSurgeon");
    $("divSurgeon1").appendChild(myP);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pSurgeonMsg1");
    $("divSurgeon1").appendChild(myP);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pSurgeonMsg2");
    $("divSurgeon1").appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnPrep");
    myButton.innerHTML = "Prep";
    $("divSurgeon1").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnMakeIncision");
    myButton.innerHTML = "Make Incision";
    $("divSurgeon1").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnStopNow");
    myButton.innerHTML = "Stop Now!";
    $("divSurgeon1").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnResumeSurgery");
    myButton.innerHTML = "Resume Surgery";
    $("divSurgeon1").appendChild(myButton);
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divSurgeon2");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "Surgical Maneuvers:";
    myP.setAttribute("id", "pSurgicalManeuvers");
    $("divSurgeon2").appendChild(myP);
    var myP = document.createElement("p");
    myP.setAttribute("id", "pSurgeonMsg3");
    $("divSurgeon2").appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnFloodField");
    myButton.innerHTML = "Flood Field";
    $("divSurgeon2").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnInsertChestTube");
    myButton.innerHTML = "Insert Chest Tube";
    $("divSurgeon2").appendChild(myButton);
    if (UserSurgeonModeStr == "waitingForPrep") {
        $("pSurgeonMsg1").innerHTML = "I am ready to prep.";
        $("pSurgeonMsg2").innerHTML = "Is the patient ready?";
		$("btnPrep").classList.remove('disabled');
		$("btnPrep").style.pointerEvents = 'auto';
		$("btnMakeIncision").classList.add('disabled');
		$("btnMakeIncision").style.pointerEvents = 'none';
		$("btnStopNow").classList.add('disabled');
		$("btnStopNow").style.pointerEvents = 'none';
		$("btnResumeSurgery").classList.add('disabled');
		$("btnResumeSurgery").style.pointerEvents = 'none';
		$("btnFloodField").classList.add('disabled');
		$("btnFloodField").style.pointerEvents = 'none';
    } else if (UserSurgeonModeStr == "prepping") {
		$("pSurgeonMsg1").innerHTML = "I am prepping and draping the patient now.";
		$("pSurgeonMsg2").innerHTML = "I will be ready to make the incision soon.";
		$("btnPrep").classList.add('disabled');
		$("btnPrep").style.pointerEvents = 'none';
		$("btnMakeIncision").classList.add('disabled');
		$("btnMakeIncision").style.pointerEvents = 'none';
		$("btnStopNow").classList.add('disabled');
		$("btnStopNow").style.pointerEvents = 'none';
		$("btnResumeSurgery").classList.add('disabled');
		$("btnResumeSurgery").style.pointerEvents = 'none';
		$("btnFloodField").classList.add('disabled');
		$("btnFloodField").style.pointerEvents = 'none';
    } else if (UserSurgeonModeStr == "readyToMakeIncision") {
		$("pSurgeonMsg1").innerHTML = "I am done prepping and draping the patient.";
		$("pSurgeonMsg2").innerHTML = "Is the patient ready for incision?";
		$("btnPrep").classList.add('disabled');
		$("btnPrep").style.pointerEvents = 'none';
		$("btnMakeIncision").classList.remove('disabled');
		$("btnMakeIncision").style.pointerEvents = 'auto';
		$("btnStopNow").classList.add('disabled');
		$("btnStopNow").style.pointerEvents = 'none';
		$("btnResumeSurgery").classList.add('disabled');
		$("btnResumeSurgery").style.pointerEvents = 'none';
		$("btnFloodField").classList.add('disabled');
		$("btnFloodField").style.pointerEvents = 'none';
    } else if (UserSurgeonModeStr == "makingIncision") {
        $("pSurgeonMsg1").innerHTML = "I am making the incision.";
        $("pSurgeonMsg2").innerHTML = "";
		$("btnPrep").classList.add('disabled');
		$("btnPrep").style.pointerEvents = 'none';
		$("btnMakeIncision").classList.add('disabled');
		$("btnMakeIncision").style.pointerEvents = 'none';
		$("btnStopNow").classList.remove('disabled');
		b$("btnStopNow").style.pointerEvents = 'auto';
		$("btnResumeSurgery").classList.add('disabled');
		$("btnResumeSurgery").style.pointerEvents = 'none';
		$("btnFloodField").classList.remove('disabled');
		$("btnFloodField").style.pointerEvents = 'auto';
        
    } else if (UserSurgeonModeStr == "operating") {
        $("pSurgeonMsg1").innerHTML = "Operating...";
		$("btnPrep").classList.add('disabled');
		$("btnPrep").style.pointerEvents = 'none';
		$("btnMakeIncision").classList.add('disabled');
		$("btnMakeIncision").style.pointerEvents = 'none';
		$("btnStopNow").classList.remove('disabled');
		$("btnStopNow").style.pointerEvents = 'auto';
		$("btnResumeSurgery").classList.add('disabled');
		$("btnResumeSurgery").style.pointerEvents = 'none';
		$("btnFloodField").classList.remove('disabled');
		$("btnFloodField").style.pointerEvents = 'auto';
    } else if (UserSurgeonModeStr == "closing") {
        $("pSurgeonMsg1").innerHTML = "I am closing.";
        $("pSurgeonMsg2").innerHTML = "I should be done soon.";
		$("btnPrep").classList.add('disabled');
		$("btnPrep").style.pointerEvents = 'none';
		$("btnMakeIncision").classList.add('disabled');
		$("btnMakeIncision").style.pointerEvents = 'none';
		$("btnStopNow").classList.remove('disabled');
		$("btnStopNow").style.pointerEvents = 'auto';
		$("btnResumeSurgery").classList.remove('disabled');
		$("btnResumeSurgery").style.pointerEvents = 'auto';
		$("btnFloodField").classList.remove('disabled');
		$("btnFloodField").style.pointerEvents = 'auto';
    } else if (UserSurgeonModeStr == "done") {
        $("pSurgeonMsg1").innerHTML = "The procedure is done. The wound is closed. The bandages are on.";
        $("pSurgeonMsg2").innerHTML = "Is the patient ready to go to recovery room?";
		$("btnPrep").classList.add('disabled');
		$("btnPrep").style.pointerEvents = 'none';
		$("btnMakeIncision").classList.add('disabled');
		$("btnMakeIncision").style.pointerEvents = 'none';
		$("btnStopNow").classList.add('disabled');
		$("btnStopNow").style.pointerEvents = 'none';
		$("btnResumeSurgery").classList.add('disabled');
		$("btnResumeSurgery").style.pointerEvents = 'none';
		$("btnFloodField").classList.add('disabled');
		$("btnFloodField").style.pointerEvents = 'none';
    } else if (UserSurgeonModeStr == "stopped") {
        $("pSurgeonMsg1").innerHTML = "You requested that I stop the surgery.";
        $("pSurgeonMsg2").innerHTML = "Can I resume now?";
		$("btnPrep").classList.add('disabled');
		$("btnPrep").style.pointerEvents = 'none';
		$("btnMakeIncision").classList.add('disabled');
		$("btnMakeIncision").style.pointerEvents = 'none';
		$("btnStopNow").classList.add('disabled');
		$("btnStopNow").style.pointerEvents = 'none';
		$("btnResumeSurgery").classList.remove('disabled');
		$("btnResumeSurgery").style.pointerEvents = 'auto';
		$("btnFloodField").classList.remove('disabled');
		$("btnFloodField").style.pointerEvents = 'auto';
    } else if (UserSurgeonModeStr == "floodingField") {
        $("pSurgeonMsg1").innerHTML = "I am flooding the field.";
        $("pSurgeonMsg2").innerHTML = ""
    } else if (UserSurgeonModeStr == "insertingChestTube") {
        $("pSurgeonMsg1").innerHTML = "I am inserting the chest tube."
    }
    $("btnPrep").observe("click", ClickBtnPrep);
    $("btnMakeIncision").observe("click", ClickBtnMakeIncision);
    $("btnStopNow").observe("click", ClickBtnStopNow);
    $("btnResumeSurgery").observe("click", ClickBtnResumeSurgery);
    $("btnFloodField").observe("click", ClickBtnFloodField);
    $("btnInsertChestTube").observe("click", ClickBtnInsertChestTube)
}



function ClickBtnPrep() {
	$("btnPrep").classList.add('disabled');
	$("btnPrep").style.pointerEvents = 'none';
	$("btnMakeIncision").classList.add('disabled');
	$("btnMakeIncision").style.pointerEvents = 'none';
    $("pSurgeonMsg1").innerHTML = "I am prepping and draping the patient now.";
    $("pSurgeonMsg2").innerHTML = "I will be ready to make the incision soon.";
    UserSurgeonModeStr = "prepping";
    SurgeonStartTime = CaseTimeInSec;
    CaseLogStr2 = CaseLogStr2.concat("Prep started.\n")
}


function ClickBtnMakeIncision() {
	$("btnPrep").classList.add('disabled');
	$("btnPrep").style.pointerEvents = 'none';
	$("btnMakeIncision").classList.add('disabled');
	$("btnMakeIncision").style.pointerEvents = 'none';
	$("btnStopNow").classList.remove('disabled');
	$("btnStopNow").style.pointerEvents = 'auto';
	$("btnFloodField").classList.remove('disabled');
	$("btnFloodField").style.pointerEvents = 'auto';
    $("pSurgeonMsg1").innerHTML = "I am making the incision.";
    $("pSurgeonMsg2").innerHTML = "";
    UserSurgeonModeStr = "makingIncision";
    UserMakeIncisionFlag = true;
    SurgeonStartTime = CaseTimeInSec;
    CaseLogStr2 = CaseLogStr2.concat("Procedure started.\n")
}


function ClickBtnStopNow() {
    $("pSurgeonMsg1").innerHTML = "You requested that I stop the surgery.";
    $("pSurgeonMsg2").innerHTML = "Can I resume now?";
	$("btnStopNow").classList.add('disabled');
	$("btnStopNow").style.pointerEvents = 'none';
	$("btnResumeSurgery").classList.remove('disabled');
	$("btnResumeSurgery").style.pointerEvents = 'auto';
	$("btnFloodField").classList.remove('disabled');
	$("btnFloodField").style.pointerEvents = 'auto';
    UserSurgeonModeStr = "stopped";
    SurgeonStopTime = CaseTimeInSec;
    CaseLogStr2 = CaseLogStr2.concat("Surgery paused.\n")
}

function ClickBtnResumeSurgery() {
    $("pSurgeonMsg1").innerHTML = "Operating...";
    $("pSurgeonMsg2").innerHTML = "";
    $("pSurgeonMsg3").innerHTML = "";
	$("btnStopNow").classList.remove('disabled');
	$("btnStopNow").style.pointerEvents = 'auto';
	$("btnResumeSurgery").classList.add('disabled');
	$("btnResumeSurgery").style.pointerEvents = 'none';
	$("btnFloodField").classList.remove('disabled');
	$("btnFloodField").style.pointerEvents = 'auto';
    UserSurgeonModeStr = "operating";
    SurgeonStartTime = SurgeonStartTime + (CaseTimeInSec - SurgeonStopTime);
    CaseLogStr2 = CaseLogStr2.concat("Surgery resumed.\n")
}

function ClickBtnFloodField() {
    CaseLogStr2 = CaseLogStr2.concat("Surgeon flooded the field.\n");
    UserFloodedFieldFlag = true;
    if ((UserSurgeonModeStr == "operating") || (UserSurgeonModeStr == "makingIncision")) {
        $("pSurgeonMsg3").innerHTML = "The surgical field was flooded. Can I resume surgery?";
        ClickBtnStopNow()
    } else {
        $("pSurgeonMsg3").innerHTML = "The surgical field was flooded."
    }
}

function ClickBtnInsertChestTube() {
    CaseLogStr2 = CaseLogStr2.concat("Chest tube inserted.\n");
            $("btnInsertChestTube").classList.add('disabled');
            $("btnInsertChestTube").style.pointerEvents = 'none';
    UserInsertedChestTubeFlag = true;
    if ((UserSurgeonModeStr == "operating") || (UserSurgeonModeStr == "makingIncision")) {
        $("pSurgeonMsg3").innerHTML = "Chest tube was inserted. Can I resume surgery?";
        ClickBtnStopNow()
    } else {
        $("pSurgeonMsg3").innerHTML = "Chest tube was inserted."
    }
}



function ShowResuscitateScreen() {
	UserShowingCenter = "resuscitate"; 
    UserShowingWhatNowFlag = false;
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divResus1");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "Resuscitation";
    myP.setAttribute("id", "pResuscitate");
    $("divResus1").appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnCallForHelp");
    myButton.innerHTML = "Call For Help";
    $("divResus1").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnAspirateCvp");
    myButton.innerHTML = "Aspirate CVP";
    $("divResus1").appendChild(myButton);
    var myP = document.createElement("p");
    myP.innerHTML = "";
	myP.show();
    myP.setAttribute("id", "pResusMsg");
    $("divResus1").appendChild(myP);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnStartCpr");
    myButton.innerHTML = "Start CPR";
    $("divResus1").appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnStopCpr");
    myButton.innerHTML = "Stop CPR";
    $("divResus1").appendChild(myButton);
	
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divResus2");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "Defibrillator";
    myP.setAttribute("id", "pDefibrillator");
    $("divResus2").appendChild(myP);
    var myP = document.createElement("p");
    myP.innerHTML = "Energy:";
    myP.setAttribute("id", "pEnergy");
    var mySelect = document.createElement("select");
    mySelect.setAttribute("id", "selEnergy");
    var myOption = document.createElement("option");
    myOption.innerHTML = "10";
    myOption.setAttribute("value", 10);
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "20";
    myOption.setAttribute("value", 20);
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "30";
    myOption.setAttribute("value", 30);
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "50";
    myOption.setAttribute("value", 50);
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "100";
    myOption.setAttribute("value", 100);
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "200";
    myOption.setAttribute("value", 200);
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "300";
    myOption.setAttribute("value", 300);
    mySelect.appendChild(myOption);
    var myOption = document.createElement("option");
    myOption.innerHTML = "360";
    myOption.setAttribute("value", 360);
    mySelect.appendChild(myOption);
    myP.appendChild(mySelect);
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "selEnergy";
    myLabel.appendChild(document.createTextNode("Joules"));
    myP.appendChild(myLabel);
    $("divResus2").appendChild(myP);
    var myDiv = document.createElement("div");
    var myCheckbox = document.createElement("input");
    myCheckbox.setAttribute("type", "checkbox");
    myCheckbox.setAttribute("id", "cbSync");
    var myLabel = document.createElement("label");
    myLabel.htmlFor = "cbSync";
    myLabel.appendChild(document.createTextNode("Synchronize"));
    myDiv.appendChild(myCheckbox);
    myDiv.appendChild(myLabel);
    $("divResus2").appendChild(myDiv);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnDischarge");
    myButton.innerHTML = "All Clear! Discharge!";
    $("divResus2").appendChild(myButton);
	
	if (UserCalledForHelpFlag) {
		$("pResusMsg").show();
            $("btnCallForHelp").classList.add('disabled');
            $("btnCallForHelp").style.pointerEvents = 'none';
	} else {
		$("pResusMsg").innerHTML = "";
            $("btnCallForHelp").classList.remove('disabled');
            $("btnCallForHelp").style.pointerEvents = 'auto';
	}
	if (UserInsertedCvpFlag) {
            $("btnAspirateCvp").classList.remove('disabled');
            $("btnAspirateCvp").style.pointerEvents = 'auto';
	} else {
            $("btnAspirateCvp").classList.add('disabled');
            $("btnAspirateCvp").style.pointerEvents = 'none';
	}
	if (UserDoingCprFlag) {
            $("btnStartCpr").classList.add('disabled');
            $("btnStartCpr").style.pointerEvents = 'none';
            $("btnStopCpr").classList.remove('disabled');
            $("btnStopCpr").style.pointerEvents = 'auto';
	} else {
            $("btnStartCpr").classList.remove('disabled');
            $("btnStartCpr").style.pointerEvents = 'auto';
            $("btnStopCpr").classList.add('disabled');
            $("btnStopCpr").style.pointerEvents = 'none';
	}
    $("btnCallForHelp").observe("click", ClickBtnCallForHelp);
    $("btnAspirateCvp").observe("click", ClickBtnAspirateCvp);
    $("btnStartCpr").observe("click", ClickBtnStartCpr);
    $("btnStopCpr").observe("click", ClickBtnStopCpr);
    $("btnDischarge").observe("click", ClickBtnDischarge)
}


function ClickBtnCallForHelp() {
            $("btnCallForHelp").classList.add('disabled');
            $("btnCallForHelp").style.pointerEvents = 'none';
    $("pResusMsg").innerHTML = "Called for help. Trained assistants have arrived and will follow your instructions.";
    $("pResusMsg").show();
    CaseLogStr2 = CaseLogStr2.concat("Called for help.\n");
    UserCalledForHelpFlag = true
}

function ClickBtnAspirateCvp() {
    $("pResusMsg").innerHTML = CurrentState.aspirateCvpMsg;
    $("pResusMsg").show();
    CaseLogStr2 = CaseLogStr2.concat(CurrentState.aspirateCvpMsg + "\n");
    UserAspiratedCvpFlag = true
}

function ClickBtnDischarge() {
    UserDefibedEnergy = parseFloat($("selEnergy").value);
    UserSyncedFlag = $("cbSync").checked;
    if (UserSyncedFlag == false) {
        CaseLogStr2 = CaseLogStr2.concat("Defib:" + UserDefibedEnergy + " Joules\n")
    } else {
        CaseLogStr2 = CaseLogStr2.concat("Sync:" + UserDefibedEnergy + " Joules\n")
    }
    HemoZapCount = 1;
            $("btnStartCpr").classList.remove('disabled');
            $("btnStartCpr").style.pointerEvents = 'auto';
            $("btnStopCpr").classList.add('disabled');
            $("btnStopCpr").style.pointerEvents = 'none';
    UserDoingCprFlag = false;
    HemoCprCount = 0
}

function ClickBtnStartCpr() {
            $("btnStartCpr").classList.add('disabled');
            $("btnStartCpr").style.pointerEvents = 'none';
            $("btnStopCpr").classList.remove('disabled');
            $("btnStopCpr").style.pointerEvents = 'auto';
    CaseLogStr2 = CaseLogStr2.concat("Started CPR.\n");
    UserDoingCprFlag = true;
    HemoCprCount = 1
}

function ClickBtnStopCpr() {
            $("btnStartCpr").classList.remove('disabled');
            $("btnStartCpr").style.pointerEvents = 'auto';
            $("btnStopCpr").classList.add('disabled');
            $("btnStopCpr").style.pointerEvents = 'none';
    CaseLogStr2 = CaseLogStr2.concat("Stopped CPR.\n");
    UserDoingCprFlag = false;
    HemoCprCount = 0
}

function ShowCaseLogScreen() {
	UserShowingCenter = "caselog"; 
    UserShowingWhatNowFlag = false;
    CaseLogStr1 = "" + "Anesthesia ";
    CaseLogStr1 = CaseLogStr1.concat(CurrentCase.title + "\n");
    CaseLogStr1 = CaseLogStr1.concat("Grade: " + GradeStr + "\n");
    CaseLogStr1 = CaseLogStr1.concat("Score: " + Score + " / " + CurrentCase.possiblePoints + "\n\n");
    if ((CurrentState.finalState != 0) && (CurrentState.helpFlag)){
        CaseLogStr1 = CaseLogStr1.concat(CurrentCase.debriefMsg + "\n\n");
    }
    $("divDisplayContent").innerHTML = "";
    var divWrapper = document.createElement("div");
    divWrapper.setAttribute("id", "divCaseLogWrapper");
    $("divDisplayContent").appendChild(divWrapper);
    var divScroll = document.createElement("div");
    divScroll.setAttribute("id", "caseLogScroller");
    $("divCaseLogWrapper").appendChild(divScroll);
    var preTxt = document.createElement("pre");
    preTxt.innerHTML = CaseLogStr1 + CaseLogStr2;
    $("caseLogScroller").appendChild(preTxt);
    CreateScroller("caseLogScroller");          
    $("divCaseLog2").show();
    $("btnSaveCaseLog").show(); // Always show the save button
    $("txtSavedCaseLog").hide(); // Initially hide the saved message
    $("btnSaveCaseLog").observe("click", ClickBtnSaveCaseLog);
}

function ClickBtnSaveCaseLog() {
    // Call saveCaseData to save case using new API file
    saveCaseData(function() {
        $("btnSaveCaseLog").hide();
        $("txtSavedCaseLog").innerHTML = "Case Log saved.";
        $("txtSavedCaseLog").show();
    });
}

function ClickBtnNewCase() {
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divExitCase");
    $("divDisplayContent").appendChild(myDiv);
    var myP = document.createElement("p");
    myP.innerHTML = "Exit Current Case";
    myP.setAttribute("id", "pExitCase");
    myDiv.appendChild(myP);
     var myP = document.createElement("p");
    myP.innerHTML = "Would you like to save your case before leaving?";
    myP.setAttribute("id", "pExitQuestion");
    myDiv.appendChild(myP);
   var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnExitSave");
    myButton.innerHTML = "Save & Exit";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnExitCase");
    myButton.innerHTML = "Exit without Saving";
    myDiv.appendChild(myButton);
    var myButton = document.createElement("button");
    myButton.setAttribute("id", "btnExitReturn");
    myButton.innerHTML = "Cancel";
    myDiv.appendChild(myButton);
    $("btnExitSave").observe("click", ClickBtnExitSave);
    $("btnExitCase").observe("click", ClickBtnExitCase)
    $("btnExitReturn").observe("click", ClickBtnExitReturn)
}

function ClickBtnExitSave() {
	saveCaseData(function() {
		clearTimeout(MyTimeout);
		ClickedStartNewCase();
	});
}

function ClickBtnExitCase() {
    clearTimeout(MyTimeout);
/* 	NOW DO THE FUNCTION THAT BROUGHT YOU HERE */
	ClickedStartNewCase();
}

function ClickBtnExitReturn() {
	ShowCaseLogScreen();
}

function ClickedStartNewCase() {
    clearTimeout(MyTimeout);
    $("imgPatient").src = "app/images/blank.jpg";
    $("imgBagVent").src = "app/images/" + UserImageStr + "/circle_spontFlat.jpg";
    $('btnTime').innerHTML = "00:00:00";
    $('txtScore').textContent = "Score: 0 / 1000";
    $("txtCaseTitle").innerHTML = "";
    $("txtHr").innerHTML = "";
    $("txtII").innerHTML = "   ";
    $("txtV5").innerHTML = "   ";
    $("txtP1").innerHTML = "NBP";
    $("divP1sdm").hide();
    $("divP1single").hide();
    $("btnGo").hide();
    $("txtMin").hide();
    $("txtSpo2Sat").innerHTML = "";
    $("txtSpo2Hr").innerHTML = "";
    $("txtSpo2signal").innerHTML = "";
    $("txtPip").innerHTML = "";
    $("txtPeep").innerHTML = "";
    $("txtTv").innerHTML = "";
    $("txtRr").innerHTML = "";
    HemoContext.clearRect(1, 1, 484, 510);
    ShowNewCaseScreen()
}

// case save modal confirmation
function showCaseSaveModal(isSuccess, errorType, message, onComplete) {
    var existingModal = document.getElementById('caseSaveModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    var modal = document.createElement('div');
    modal.id = 'caseSaveModal';
    modal.className = 'modal';
    modal.style.display = 'flex';
    
    var modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    
    if (isSuccess === null) {
        var heading = document.createElement('h2');
        heading.textContent = 'Saving...';
        var paragraph = document.createElement('p');
        paragraph.textContent = 'Please wait while your case is being saved.';
        modalContent.appendChild(heading);
        modalContent.appendChild(paragraph);
    } else {
        var heading = document.createElement('h2');
        var paragraph = document.createElement('p');
        
        if (isSuccess) {
            heading.textContent = 'Success';
            paragraph.textContent = 'Case log was saved to your account.';
        } else {
            var errorMessages = {
                // 'SESSION_EXPIRED': 'Your session has expired. Please log in again and retry saving. If needed, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com',
                'SESSION_EXPIRED': 'SESSION_FORM_NEEDED','CONNECTION_ERROR': 'Unable to communicate with server. Please try saving again in a few moments. If unsuccessful, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com',
                'TIMEOUT_ERROR': 'Server is currently busy. Please wait a moment and try again. If unsuccessful after several attempts, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com',
                'DATABASE_ERROR': 'Database temporarily unavailable. Please try again in a few minutes. If the problem continues, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com',
                'VALIDATION_ERROR': 'Invalid data detected in case log. Please review your entries and try again. If you need assistance, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com',
                'NETWORK_ERROR': 'Network connection problem detected. Check your internet connection and try again. If the problem persists, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com',
                'GENERAL_ERROR': 'An unexpected error occurred. Please try again. If the problem persists, open the case log, copy all text and save in a txt file or Word doc. Contact jill@website.com'
            };
            
            heading.textContent = 'Save Failed';
            paragraph.textContent = message || errorMessages[errorType] || errorMessages['GENERAL_ERROR'];
        }
        
        if (errorType === 'SESSION_EXPIRED') {
            modal.remove();
            showSessionFailureModal();
        } else {
            var continueBtn = document.createElement('button');
            continueBtn.textContent = 'Continue';
            continueBtn.className = isSuccess ? 'saveExit' : 'continueExit';
            continueBtn.onclick = function() { 
                modal.remove();
                if (onComplete) onComplete();
            };
            
            modalContent.appendChild(heading);
            modalContent.appendChild(paragraph);
            modalContent.appendChild(continueBtn);
        }
    }
    
    modal.appendChild(modalContent);
    document.body.appendChild(modal);
}

// session faire modal
function showSessionFailureModal() {
    var modal = document.getElementById('sessionFailureModal');
    if (!modal) return;
    
    var getOS = function() {
        var ua = navigator.userAgent;
        if (ua.indexOf('Win') !== -1) return 'Windows';
        if (ua.indexOf('Mac') !== -1) return 'macOS';
        if (ua.indexOf('Linux') !== -1) return 'Linux';
        if (ua.indexOf('Android') !== -1) return 'Android';
        if (ua.indexOf('iOS') !== -1) return 'iOS';
        return 'Unknown';
    };
    
    var getBrowser = function() {
        var ua = navigator.userAgent;
        if (ua.indexOf('Firefox') !== -1) return 'Firefox';
        if (ua.indexOf('Chrome') !== -1) return 'Chrome';
        if (ua.indexOf('Safari') !== -1 && ua.indexOf('Chrome') === -1) return 'Safari';
        if (ua.indexOf('Edge') !== -1) return 'Edge';
        return 'Unknown';
    };
    
    document.getElementById('osInfo').value = getOS();
    document.getElementById('browserInfo').value = getBrowser() + ' (' + navigator.userAgent + ')';
    
    modal.style.display = 'flex';
    
    document.getElementById('skipSessionReport').onclick = function() {
        modal.style.display = 'none';
        window.location.href = '/login.php';
    };
    
    document.getElementById('sessionFailureForm').onsubmit = function(e) {
        e.preventDefault();
        
        var reportData = {
            actionsBeforeFailure: document.getElementById('actionsBeforeFailure').value,
            timeWorking: document.getElementById('timeWorking').value,
            osInfo: document.getElementById('osInfo').value,
            browserInfo: document.getElementById('browserInfo').value,
            additionalNotes: document.getElementById('additionalNotes').value,
            userAgent: navigator.userAgent,
            screenResolution: screen.width + 'x' + screen.height,
            viewportSize: window.innerWidth + 'x' + window.innerHeight,
            connectionType: navigator.connection ? navigator.connection.effectiveType : 'Unknown',
            onlineStatus: navigator.onLine,
            cookiesEnabled: navigator.cookieEnabled,
            localStorageAvailable: typeof(Storage) !== 'undefined',
            sessionStorageAvailable: typeof(Storage) !== 'undefined',
            pageUrl: window.location.href,
            referrer: document.referrer
        };
        
        fetch('/api/log_session_failure.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(reportData)
        }).then(function() {
            modal.style.display = 'none';
            window.location.href = '/login.php';
        }).catch(function(err) {
            console.error('Failed to submit report:', err);
            modal.style.display = 'none';
            window.location.href = '/login.php';
        });
    };
}

// Case data saving function
function saveCaseData(onComplete) {
    // Check session validity before attempting save
    fetch('/api/check_session.php')
        .then(response => response.json())
        .then(sessionData => {
            if (!sessionData.valid || sessionData.expired) {
                // Session expired - trigger reauth modal immediately
                var modal = document.getElementById('reauthModal');
                if (modal) {
                    modal.style.display = 'flex';
                    modal.classList.add('modal-active');
                    
                    // Make modal non-dismissible
                    modal.onclick = function(e) {
                        if (e.target === modal) {
                            e.stopPropagation();
                            return false;
                        }
                    };
                } else {
                    alert('Your session has expired. Please refresh and log in again.');
                }
                return; // Don't proceed with save
            }
            
            // Session is valid - proceed with save
            performCaseSave(onComplete);
        })
        .catch(error => {
            console.error('Session check failed:', error);
            // Proceed with save anyway in case of network issues
            performCaseSave(onComplete);
        });
}

function performCaseSave(onComplete) {
    var caseLogElement = document.querySelector("#caseLogScroller pre");
    var grade, score;
    if (caseLogElement) {
        var caseLog = caseLogElement.innerText;
        console.log("Case log extracted:", caseLog.length, "chars");
    } else {
        console.error("Case log not found");
        caseLog = null;
    }
    var gradeMatch = caseLog.match(/Grade: (\w+)/);
    if (gradeMatch) {
        grade = gradeMatch[1];
    } else {
        grade = "Unknown";
    }
    var scoreElement = document.getElementById("txtScore");
    if (scoreElement) {
        var scoreText = scoreElement.innerText;
        var scoreMatch = scoreText.match(/Score: (\d+) \/ \d+/);
        if (scoreMatch) {
            score = scoreMatch[1];
        } else {
            score = null;
        }
    } else {
        score = null;
    }
    
    showCaseSaveModal(null, null, "Saving case...", null);
    
    // Extract score from HTML
    var scoreText = document.getElementById('txtScore')?.textContent || '';
    var scoreMatch = scoreText.match(/(-?\d+\s*\/\s*\d+)/);
    var currentScore = scoreMatch ? scoreMatch[0] : '0 / 0';
    
    // Extract time from HTML
    var timeText = document.getElementById('btnTime')?.textContent || '00:00:00';

    // Extract case name from HTML
    var caseName = document.getElementById('txtCaseTitle')?.textContent || 'Unknown Case';

    var data = {
        caseLog: caseLog,
        grade: grade,
        instructor_notes: null,
        clientUserId: document.getElementById('hiddenUserId')?.value,
        clientUserFirstName: document.getElementById('hiddenUserFirstName')?.value,
        clientUserLastName: document.getElementById('hiddenUserLastName')?.value,
        clientUserEmail: document.getElementById('hiddenUserEmail')?.value,
        clientUserGroup: document.getElementById('hiddenUserGroup')?.value,
        clientCaseScore: currentScore,
        clientCaseTime: timeText.trim(),
        clientCaseName: caseName.trim(),
        debugData: {
            timestamp: new Date().toISOString(),
            pageLoadTime: performance.timing ? (Date.now() - performance.timing.navigationStart) : 'unknown',
            memoryUsage: performance.memory ? performance.memory.usedJSHeapSize : 'unknown',
            connectionType: navigator.connection ? navigator.connection.effectiveType : 'unknown',
            onlineStatus: navigator.onLine,
            cookiesEnabled: navigator.cookieEnabled,
            sessionStorageWorks: (function() {try{sessionStorage.setItem('test','1');sessionStorage.removeItem('test');return true;}catch(e){return false;}})(),
            localStorageWorks: (function() {try{localStorage.setItem('test','1');localStorage.removeItem('test');return true;}catch(e){return false;}})()
        }
    };
    fetch("/api/save_case_data.php", {
        method: "POST",
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    }).then(response => response.json())
      .then(data => {
          console.log("Server response:", data);
          if (data.success) {
              showCaseSaveModal(true, null, "Case log was saved to your account.", onComplete);
          } else {
              showCaseSaveModal(false, data.errorType, data.message || "Case log was NOT saved. Please try again.", onComplete);
          }
      }).catch(error => {
          console.error("Network error:", error);
          console.error("Error type:", error.name);
          console.error("Error message:", error.message);
          showCaseSaveModal(false, 'NETWORK_ERROR', "Network error. Please check your connection and try again.", onComplete);
      });
}

/* initialize  new case data */

window.isDemoUser = false; // Default value, will be updated by loadCaseData

function ShowNewCaseScreen() {
	UserShowingCenter = "newcase"; 
    // console.log('ShowNewCaseScreen called');

    UserShowingWhatNowFlag = false;
    UserCaseRunning = false;
	stopSessionKeepalive();
    // console.log('Setting display properties');
    $("tableAgm").style.display = "none";
    $("lblPip").hide();
    $("lblPeep").hide();
    $("lblTv").hide();
    $("lblRr").hide();
    $("txtTemperature").hide();
    UserN2OFlow = parseFloat(0);
    $("seldivN2O").value = UserN2OFlow;
    UserAirFlow = parseFloat(0);
    $("seldivAir").value = UserAirFlow;
    UserO2Flow = parseFloat(5);
    $("seldivO2").value = UserO2Flow;
    UserVaporizerAmount = parseFloat(0);
    $("selVapAmount").value = UserVaporizerAmount;
    RefreshBobbin();
    DisableSideMenu();
            $("seldivN2O").classList.add('disabled');
            $("seldivN2O").style.pointerEvents = 'none';
            $("seldivAir").classList.add('disabled');
            $("seldivAir").style.pointerEvents = 'none';
            $("seldivO2").classList.add('disabled');
            $("seldivO2").style.pointerEvents = 'none';
            $("selVaporizer").classList.add('disabled');
            $("selVaporizer").style.pointerEvents = 'none';
            $("selVapAmount").classList.add('disabled');
            $("selVapAmount").style.pointerEvents = 'none';
            $("btnGo").classList.add('disabled');
            $("btnGo").style.pointerEvents = 'none';

    // console.log('Clearing display content');
    $("divDisplayContent").innerHTML = "";
    $("divCaseLog2").hide();

// was    // console.log('Adding splash image');
    var myImage = document.createElement("img");
    myImage.setAttribute("id", "imgSplash");
    $("divDisplayContent").appendChild(myImage);
    $("imgSplash").src = "app/images/anesthSplash.jpg";
	

// was    // console.log('Creating case selector');
    var myDiv = document.createElement("div");
    myDiv.setAttribute("id", "divSelectCase"); 
    $("divDisplayContent").appendChild(myDiv);

// was    // console.log('Creating select element');
    var selectlist = document.createElement("select");
    selectlist.setAttribute("id", "caseList");
    selectlist.setAttribute("name", "caseList");
    $("divSelectCase").appendChild(selectlist);


// was    // console.log('Adding default option');
    var option = document.createElement("option");
    option.setAttribute("value", "defaultCase");
    option.innerHTML = "Select a Case to Start";
    selectlist.appendChild(option);

// was    // console.log('Loading case data');
    loadCaseData(function(caseData) {
// was        // console.log('Case data loaded, populating list');
        populateCaseList(selectlist, caseData);
    });

// was    // console.log('Adding change event listener');
    $("caseList").observe("change", SetCurrentCase);

// imgSplash was here
// was    // console.log('ShowNewCaseScreen completed');
}

function loadCaseData(callback) {
    Promise.all([
        fetch('api/get_case_data.php').then(response => response.json()),
        fetch('api/get_pro_status.php').then(response => response.json()),
        fetch('api/demo_role.php').then(response => response.text())
    ])
    .then(([caseData, proStatus, isDemo]) => {
		// debug
	//	console.log('Pro status response:', proStatus);
		
        // First load check
        const reloadCount = localStorage.getItem('reload_count') || '0';
        
        if(reloadCount === '0') {
            // First load - store initial status
            localStorage.setItem('demo_status', caseData.some(c => c.requiresUpgrade));
            localStorage.setItem('pro_status', proStatus.isPro);
            localStorage.setItem('reload_count', '1');
            
            window.isPro = proStatus.isPro;
            window.isDemoUser = caseData.some(c => c.requiresUpgrade);
        } else if(reloadCount === '1') {
            // First reload - use stored values
            window.isPro = localStorage.getItem('pro_status') === 'true';
            window.isDemoUser = localStorage.getItem('demo_status') === 'true';
            
            // Clear everything after first reload
            localStorage.removeItem('demo_status');
            localStorage.removeItem('pro_status');
            localStorage.removeItem('reload_count');
        } else {
            // Fresh check
            window.isPro = proStatus.isPro;
            window.isDemoUser = caseData.some(c => c.requiresUpgrade);
        }
        
        window.allCases = caseData;
        callback(caseData);
    })
    .catch(error => {
        console.log('Error loading Pro data: ', error);
    });
}

function populateCaseList(selectElement, cases) {
    // console.log('Populating cases for demo user:', window.isDemoUser);
    
    selectElement.innerHTML = '<option value="defaultCase">Select a Case to Start</option>';

    cases.forEach(function(caseItem) {
        var option = document.createElement("option");
        option.value = caseItem.id;
        option.textContent = caseItem.title;
        
        // Demo user handling for cases 2-40
        if (window.isDemoUser && caseItem.id !== 1 && caseItem.id <= 40) {
            option.textContent += ' (Upgrade)';
            option.classList.add('demo-user');
            option.style.color = '#999';
            // console.log('Demo case restricted:', caseItem.id);
        }
        
        // Pro user handling (working, leave as is)
        if (caseItem.isPro && !window.isPro) {
            option.textContent += ' (Pro Only)';
            option.classList.add('pro-only');
        }
        
                selectElement.appendChild(option);
    });

    selectElement.addEventListener('change', function(event) {
        const selectedValue = this.value;
        // console.log('Selection changed to:', selectedValue);
        
        if (selectedValue === 'defaultCase') {
            resetSelection(selectElement);
            return;
        }

        var selectedCase = cases.find(c => c.id == selectedValue);
        
        // Demo restriction (cases 2-40)
        if (window.isDemoUser && selectedCase.id !== 1 && selectedCase.id <= 40) {
            // console.log('Demo user attempting restricted case:', selectedCase.id);
            event.preventDefault();
            showUpgradeModal(false);
            resetSelection(selectElement);
            return;
        }
        
        // Pro restriction (cases 41+)
        if (selectedCase.isPro && !window.isPro) {
            // console.log('Non-pro user attempting pro case:', selectedCase.id);
            event.preventDefault();
            showUpgradeModal(true);
            resetSelection(selectElement);
            return;
        }

        SetCurrentCase(selectedValue);
    });
}

function resetSelection(selectElement) {
    // console.log('Resetting case selection');
    selectElement.value = 'defaultCase';
    
    if (typeof UserCaseRunning !== 'undefined' && UserCaseRunning) {
        UserCaseRunning = false;
		stopSessionKeepalive();
        if (typeof MyTimeout !== 'undefined') {
            clearTimeout(MyTimeout);
        }
        if (typeof ShowNewCaseScreen === 'function') {
            ShowNewCaseScreen();
        }
    }
}

function handleCaseSelection(event) {
    // console.log('External case selection:', event.detail);
    var caseId = event.detail.caseId;
    
    // Demo restriction check
    if (window.isDemoUser && caseId !== 1 && caseId <= 40) {
        // console.log('Demo user blocked from case:', caseId);
        showUpgradeModal(false);
        resetSelection(document.getElementById('caseList'));
        return;
    }
    
    // Pro check
    var selectedCase = window.allCases?.find(c => c.id == caseId);
    if (selectedCase?.isPro && !window.isPro) {
        showUpgradeModal(true);
        resetSelection(document.getElementById('caseList'));
        return;
    }
    
    SetCurrentCase(caseId);
}

function showUpgradeModal(isPro) {
    var modal = document.getElementById('upgradeModal');
    var titleElement = document.getElementById('modalTitle');
    var messageElement = document.getElementById('modalMessage');
    var yesButton = document.getElementById('upgradeYes');
    var noButton = document.getElementById('upgradeNo');
    
    // Set the appropriate URL based on upgrade type
    const upgradeUrl = isPro 
        ? mainUrl + '/pro'
        : mainUrl + '/upgrade';

    if (isPro) {
        titleElement.textContent = "Upgrade to Pro";
        messageElement.textContent = "This case is only available for Pro users. Would you like to upgrade?";
    } else {
        let isAdmin = window.userType === 'admin' || window.userType === 'super';
        titleElement.textContent = "Upgrade To A Full Account";
        messageElement.textContent = isAdmin ? 
            "Demo administrators have access Case 1. Please upgrade to access more cases." :
            "To access more cases, you need to upgrade to a full account.";
    }

    modal.style.display = 'block';

    yesButton.onclick = function() {
        window.open(upgradeUrl, '_blank');
        closeModal();
    };

    noButton.onclick = function() {
        closeModal();
    };

    window.onclick = function(event) {
        if (event.target === modal) {
            closeModal();
        }
    };

    function closeModal() {
        modal.style.display = 'none';
        resetCase();
    }
}

function resetCase() {
    document.getElementById('caseList').value = 'defaultCase';
    document.getElementById('txtCaseTitle').innerHTML = "";
    document.getElementById('btnGo').classList.add('disabled');
    document.getElementById('btnGo').style.pointerEvents = 'none';

    ['Hr', 'II', 'V5', 'S-D', 'M', 'Min', 'Spo2Sat', 'Spo2Hr', 'Spo2signal', 
     'I-O2', 'E-O2', 'I-Vap', 'E-Vap', 'EtCO2', 'Pip', 'Peep', 'Tv', 'Rr', 'Temperature']
    .forEach(f => {
        const element = document.getElementById(`txt${f}`);
        if (element) element.innerHTML = "";
    });
}

// event listener for case selection
document.addEventListener('caseSelected', handleCaseSelection);

// Call after starting a case and whenever the case status changes
function ShowScreenResized() {
    // Only show pause screen if a case is running and CurrentCase exists
    if (UserCaseRunning && typeof CurrentCase !== 'undefined' && CurrentCase !== null) {
        UserShowingWhatNowFlag = false;
        $("divDisplayContent").innerHTML = "";
        $("divCaseLog2").hide();
        var myDiv = document.createElement("div");
        myDiv.setAttribute("id", "divPause");
        $("divDisplayContent").appendChild(myDiv);
        var myP = document.createElement("p");
        myP.setAttribute("id", "pPause");
        myP.innerHTML = "You changed the size of the screen. The simulation was suspended.";
        myDiv.appendChild(myP);
        var linebreak = document.createElement("br");
        myDiv.appendChild(linebreak);
        var myButton = document.createElement("button");
        myButton.setAttribute("id", "btnResume");
        myButton.innerHTML = "Resume";
        myButton.classList.remove('disabled');
        myButton.style.pointerEvents = 'auto';
        myDiv.appendChild(myButton);

        $("btnResume").onclick = function() {
            $("divDisplayContent").innerHTML = "";
            resumeCase(); // Use the same resume function
        };

        DisableSideMenu();
        $("seldivN2O").classList.add('disabled');
        $("seldivN2O").style.pointerEvents = 'none';
        $("seldivAir").classList.add('disabled');
        $("seldivAir").style.pointerEvents = 'none';
        $("seldivO2").classList.add('disabled');
        $("seldivO2").style.pointerEvents = 'none';
        $("selVaporizer").classList.add('disabled');
        $("selVaporizer").style.pointerEvents = 'none';
        $("selVapAmount").classList.add('disabled');
        $("selVapAmount").style.pointerEvents = 'none';
        $("btnGo").classList.add('disabled');
        $("btnGo").style.pointerEvents = 'none';
        clearTimeout(MyTimeout);
    } else {
        ShowNewCaseScreen();
    }
}