
function probesIncoming(id, pH, min, max) {  // continually update sensor data coming from backend
    // console.log('probesIncoming = ' + id + ", " + pH + ", " + min + ", " + max);
    for (var i = 0; i < phAddrPlugged.length; i++) {  // save all pins to database
        if (phAddrPlugged[i] == id) {
            if (phCalibrateRunning[i] == 0) {  // calibration not running
                phValue[i] = pH;  // update pH
                // console.log('phValue[i] = ' + phValue[i]);
                phMinValue[i] = min;  // update min
                phMaxValue[i] = max;  // update max

                // phValue[i] = (7.0 - pH) * 59.16;  // update pH
                // // console.log('phValue[i] = ' + phValue[i]);
                // phMinValue[i] = (7.0 - min) * 59.16;  // update min
                // phMaxValue[i] = (7.0 - max) * 59.16;  // update max
                break;
            }
            else {  // calibration running
                phValue[i] = pH;  // update ph
                prevPhCalibrationTickCount = phCalibrationTickCount;
                phCalibrationTickCount = min;  // update stabilize tick counter for calibration
                phCalibrateRunning[i] = max;  // update status of calibration so we can exit when finished
                if (calibrationTypeRunning == 1) {  // single point calibration
                    if (phCalibrationTickCount == 20) {pHCalibrationFinished(); phCalibrateRunning[i] = 0;}  // mark calibration finished
                }
                else if ((calibrationTypeRunning == 2) && (phCalibratingStep == 1)) {  // dual point calibration - 1st step
                    if (phCalibrationTickCount == 20) {phCalibratingStep = 2; setTimeout(probesPhCalibrate(2),1000);}  // go to 2nd step
                }
                else if ((calibrationTypeRunning == 2) && (phCalibratingStep == 3)) {  // dual point calibration - 2nd step
                    if (phCalibrationTickCount == 20) {pHCalibrationFinished(); phCalibrateRunning[i] = 0;}  // mark calibration finished
                }
                updatePhStabilizeBox();  // update stability slider
                break;
            }
        }
    }
}

function updateProbes() {  // continually update probes data from database
    // console.log('updateProbes&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&');

    $.ajax({  // check if probe was added or unplugged
        url: "/php/phRead.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) 
        {
            // console.log('updateProbes.........................................');
            // console.log(dataWindow);
            previousPhFound = phSeen;  // store number of probes found before reading sensor data so we know if something changed
            phPlugged = [];  // reset array
            phName = [];
            phNamePlugged = [];
            phAddrSaved = [];
            phAddrPlugged = [];
            phSeen = 0;  // reset how many probes are seen
            phSaved = 0;  // tracks how many probes are in database

            for(var i in dataWindow) 
            {
                phPlugged.push(dataWindow[i].plugged);  // track if sensor is plugged in or not for table
                phName.push(dataWindow[i].name);
                phAddrSaved.push(dataWindow[i].address);  // get all addresses in database
                if (phPlugged[i] == 1)  // get custom name and address for probes plugged in
                {
                    phAddrPlugged.push(dataWindow[i].address);
                    phNamePlugged.push(dataWindow[i].name);
                    phSeen++;  // tracks how many probes are plugged in
                }
                // console.log('phNamePlugged = ' + phNamePlugged);
                phSaved++;  // track how many probes are in the database

            }
            
            if (displayScreen == 0) {printProbes();}  // print data to dashboard
            else if (displayScreen == 4) {printPhCalScreen();}  // print data to calibration screen
        },
        error: function(dataWindow) {
            // console.log('ERROR - updateProbes() -----------------------------------------------------------------');
            // console.log(dataWindow);// no sensor data
        }
    });
}

function printProbes() {  // print probe data to dashboard
    var i = 0;
    // go though each probe
    for (var i = 0; i < phSeen; i++) {  // save all pins to database
        document.getElementById('probeName' + [i]).innerHTML = phNamePlugged[i];  // update probe name
        document.getElementById('probeValue' + [i]).innerHTML = round(phValue[i], 3).toFixed(3);  // update probe value
        document.getElementById('probeMax' + [i]).innerHTML = round(phMaxValue[i], 2).toFixed(2);  // update probe max
        document.getElementById('probeMin' + [i]).innerHTML = round(phMinValue[i], 2).toFixed(2);  // update probe min
    }
}

function printPhCalScreen() {  // print pH on calibration screen
    for (var i = 0; i < phSeen; i++) {
        if (phAddrPlugged[i] == pHcalibratingAddress) {
            // console.log("round(phValue[i], 3) = " + round(phValue[i], 3));
            document.getElementById('phValue').innerHTML = round(phValue[i], 3);  // update probe text
            break;
        }
    }
}

function resetProbeMin(i) {  // reset min value
    // console.log('resetProbeMin -------------');
    var command = "30," + phAddrPlugged[i];
    sendToBackend(command);

    ds18b20Popup.style.display = "none";  // hide popup
    document.querySelector("body").style.overflow = 'visible';
    $('.ds18b20Popup-body').empty();
    $('#popupBackground').hide();  // hide greyed out background

    phMinValue[i] = phValue[i];
}

function resetProbeMax(i) {  // reset max value
    // console.log('resetProbeMax -------------');
    var command = "31," + phAddrPlugged[i];
    sendToBackend(command);

    ds18b20Popup.style.display = "none";  // hide popup
    document.querySelector("body").style.overflow = 'visible';
    $('.ds18b20Popup-body').empty();
    $('#popupBackground').hide();  // hide greyed out background

    phMaxValue[i] = phValue[i];
}

function resetProbeMinMax(i, l) {  // confirmation screen to reset min or max
    // console.log('resetProbeMinMax');
    $('#popupBackground').show();  // grey out background
    $('.ds18b20Popup-body').empty();
    ds18b20Popup.style.display = "block";
    document.querySelector("body").style.overflow = 'hidden';
    $('.ds18b20PopupHeader').empty();
    if (l == 0) {  // reset min
        $(".ds18b20PopupHeader").append("Reset Probe Minimum Value");
        $(".ds18b20Popup-body").append(
            '<div style="text-align: center;">\
                <p>&nbsp;</p>\
                <p>Are you sure you want to reset the minimum recorded value for ' + phNamePlugged[i] + '?</p>\
                <div class="widgetButtonBox">\
                    <button class="button _wide" type="button" onclick="resetProbeMin(`' + i + '`)">Yes</button>\
                    <button class="button _wide" type="button" onclick="closeDs18b20Popup()">No</button>\
                </div></br>\
            </div>');
    }
    else {  // reset max
        $(".ds18b20PopupHeader").append("Reset Probe Maximum Value");
        $(".ds18b20Popup-body").append(
            '<div style="text-align: center;">\
                <p>&nbsp;</p>\
                <p>Are you sure you want to reset the maximum recorded value for ' + phNamePlugged[i] + '?</p>\
                <div class="widgetButtonBox">\
                    <button class="button _wide" type="button" onclick="resetProbeMax(`' + i + '`)">Yes</button>\
                    <button class="button _wide" type="button" onclick="closeDs18b20Popup()">No</button>\
                </div></br>\
            </div>');
    }
}

function settingsProbes() {  // main settings screen for probes

    closeDs18b20Popup();
    printHeaderTitle("CALIBRATE PROBES", "probes2.png", "#d1d127");  // name and file

    removeFooter();

    document.getElementById('content').innerHTML =
        `<div class='cleanScreen' id='cleanScreen'>
            <div class='settingsContainer' id='container'>
                <div class="settingsTitle" id="label">Select a probe to calibrate!</div>
            </div>
            <div class='widgetButtonBox'>
                <button class='button _48 back_48' style='margin-top:10px;' type='button' onclick='viewSettingsMenu();'></button>
                <button class='button _48 home_48' style='margin-top:10px;' type='button' onclick='loadLayout();'></button>
            </div>
        </div>`;
    
    for (i = 0; i < phSeen; i++) {  // create button for each probe
        document.getElementById('container').innerHTML += 
            `<div class="settingsProbesIconBox" onclick="probesCalibrateType(` + phAddrPlugged[i] + `)">\
                <div class="settingsIcon"><img id='pHicon' class='settingsPic' src='images/icons/pH.png'></div>\
                <div class="settingsName">` + phNamePlugged[i] + `</div>\
            </div>`;
    }
}

function probesCalibrateType(address) {  // calibration type screen
    // console.log("probesCalibrateType = " + address);
    pHcalibratingAddress = address;
        
    displayScreen = 5;

    document.getElementById('content').innerHTML =
    `<div class='cleanScreen' id='cleanScreen'>
        <div class='settingsContainer' id='container'>
            <div class="settingsTitle" id="label">Select calibration method!</div>
            <div class="settingsProbesIconBox" onclick="probesPhCalibrate(1)">
            <div class="settingsIcon"><img id='pHicon' class='settingsPic' src='images/icons/pH.png'></div>
                <div class="settingsName" id='1point'>1 Point Calibration</div>
            </div>
            <div class="settingsProbesIconBox" onclick="probesPhCalibrate(2)">
                <div class="settingsIcon"><img id='pHicon' class='settingsPic' src='images/icons/pH.png'></div>
                <div class="settingsName" id='2point'>2 Point Calibration</div>
            </div>
            <div class='widgetButtonBox' style="margin-top:0px;">
                <button id="start1" class='button _wide' style='margin-top:10px; background-color:#d1d127;' type='button' onclick='phVerifyDeleteCalibration()'>Delete Calibration</button>
            </div>
        </div>
        <div class='widgetButtonBox'>
            <button class='button _48 back_48' style='margin-top:10px;' type='button' onclick='settingsProbes();'></button>
            <button class='button _48 home_48' style='margin-top:10px;' type='button' onclick='loadLayout();'></button>
        </div>
    </div>`;
}

function probesPhCalibrate(calType) {  // calibration screen for each point
    closeDs18b20Popup();
    calibrationTypeRunning = calType;  // track calibration type so we can use it later
    displayScreen = 4;
    var buffer = 1;

    var arrayID = 0;
    for (i = 0; i < phSeen; i++) {  // get array location so we can print probe info
        if (phAddrPlugged[i] == pHcalibratingAddress) {arrayID = i; break;}
    }

    if (calType == 1) {  // 1 point calibration
        var command = "34, " + pHcalibratingAddress + "," + calType + "," + round(phBuffer1,2).toFixed(2);
        sendToBackend(command);
        buffer = 1;

        phCalibratingStep = 1;

        document.getElementById('content').innerHTML =
            `<div class='cleanScreen' id='cleanScreen'>
                <div class='settingsContainer' id='container'>
                    <div class="settingsTitle" id="label">Single Point Calibration</div>
                    <ul class="numberBullets phInstructions">
                        <li class="phInstructionsLI">For a single point calibration process you should use 7.0 buffer but a lower or higher buffer is better
                            than none, adjust the buffer to match what you have.
                        </li>
                        <li class="phInstructionsLI">Rinse the probe thoroughly with distilled water to clean it then flick the probe to remove the excess rinse
                            water. Do not rub or touch the probe bulb with a cloth since it can cause a static charge build up but you can place the outside 
                            of the probe on a paper towel to absorb the water droplets.
                        </li>
                        <li class="phInstructionsLI">Insert the probe in the buffer solution and move side to side to remove trapped air bubbles.</li>
                        <li class="phInstructionsLI">Click the <b>Start</b> button to continue.</li>
                    </ul>
                    <div class="probesCalContainer">
                        <div class="probesCalBox">
                        <div class="doseSettingsAmountBox" style="width:100%;">
                            <div class="probesBufferAmountLabel" id="label">Uncalibrated pH Reading</div>
                            <div class="probesBufferAmount" id="phValue">` + phValue[arrayID] +  `</div>
                        </div>
                        </div>
                        <div class="probesCalBox">
                            <div class="doseSettingsAmountBox">
                                <div class="probesBufferAmountLabel" id="label">pH Buffer</div>
                                <div class="probesBufferAmount" id="probesBufferAmount">` + round(phBuffer1,2).toFixed(2) +  `</div>
                            </div>
                            <div class="parameterButtonBox">
                                <button id="changeBufferUp" onclick="changeBufferValue(1,0)" class="probesUpDownButton bi bi-arrow-up-short"></button></br>
                                <button id="changeBufferDown" onclick="changeBufferValue(1,1)" class="probesUpDownButton bi bi-arrow-down-short"></button>
                            </div>
                        </div>
                    </div>
                    <button id="start1" class='button _wide' style='margin-top:10px; background-color:#d1d127;' type='button' onclick='phVerifyCalibration()'>Start Calibration</button>
                </div>
                <div class='widgetButtonBox'>
                    <button class='button _48 back_48' style='margin-top:10px;' type='button' onclick='cancelProbeCalibration(0); probesCalibrateType(" + pHcalibratingAddress + ");'></button>
                    <button class='button _48 home_48' style='margin-top:10px;' type='button' onclick='cancelProbeCalibration(0); loadLayout();'></button>
                </div>
            </div>`;

        document.getElementById('label').style.color = "#d1d127";  // change label color
        document.getElementById('start1').style.backgroundColor = "#d1d127";  // change button color
    }
    else {  // 2 point calibration
        if (phCalibratingStep == 0) {  // point 1
            buffer = 1;
            var command = "34, " + pHcalibratingAddress + "," + calType + "," + round(phBuffer1,2).toFixed(2);
            sendToBackend(command);
            phCalibratingStep = 1;

            document.getElementById('content').innerHTML =
                `<div class='cleanScreen' id='cleanScreen'>\
                    <div class='settingsContainer' id='container'>
                        <div class="settingsTitle" id="label">2 Point Calibration - Point 1</div>
                        <ul class="numberBullets phInstructions">
                            <li class="phInstructionsLI">For a dual point calibration you should start with 7.0 buffer but you can adjust the buffer to
                                match what you have.
                            </li>
                            <li class="phInstructionsLI">Rinse the probe thoroughly with distilled water to clean it then flick the probe to remove the excess rinse
                                water. Do not rub or touch the probe bulb with a cloth since it can cause a static charge build up but you can place the outside 
                                of the probe on a paper towel to absorb the water droplets.
                            </li>
                            <li class="phInstructionsLI">Insert the probe in the buffer solution and move side to side to remove trapped air bubbles.</li>
                            <li class="phInstructionsLI">Click the <b>Start</b> button to continue with point 1.</li>
                        </ul>
                        <div class="probesCalContainer">
                            <div class="probesCalBox">
                            <div class="doseSettingsAmountBox" style="width:100%;">
                                <div class="probesBufferAmountLabel" id="label">Uncalibrated pH Reading</div>
                                <div class="probesBufferAmount" id="phValue">` + phValue[arrayID] +  `</div>
                            </div>
                            </div>
                            <div class="probesCalBox">
                                <div class="doseSettingsAmountBox">
                                    <div class="probesBufferAmountLabel" id="label">pH Buffer 1</div>
                                    <div class="probesBufferAmount" id="probesBufferAmount">` + round(phBuffer1,2).toFixed(2) +  `</div>
                                </div>
                                <div class="parameterButtonBox">
                                    <button id="changeBufferUp" onclick="changeBufferValue(1,0)" class="probesUpDownButton bi bi-arrow-up-short"></button></br>
                                    <button id="changeBufferDown" onclick="changeBufferValue(1,1)" class="probesUpDownButton bi bi-arrow-down-short"></button>
                                </div>
                            </div>
                        </div>
                        <button id="start1" class='button _wide' style='margin-top:10px; background-color:#d1d127;' type='button' onclick='phVerifyCalibration()'>Start Calibration</button>
                    </div>
                    <div class='widgetButtonBox'>
                        <button class='button _48 back_48' style='margin-top:10px;' type='button' onclick='cancelProbeCalibration(0); probesCalibrateType(" + pHcalibratingAddress + ");'></button>
                        <button class='button _48 home_48' style='margin-top:10px;' type='button' onclick='cancelProbeCalibration(0); loadLayout();'></button>
                    </div>
                </div>`;

            document.getElementById('label').style.color = "#d1d127";  // change label color
            document.getElementById('start1').style.backgroundColor = "#d1d127";  // change button color
        }
        else if (phCalibratingStep == 2) {  // point 2
            buffer = 2;
            document.getElementById('content').innerHTML =
                `<div class='cleanScreen' id='cleanScreen'>\
                    <div class='settingsContainer' id='container'>
                        <div class="settingsTitle" id="label">2 Point Calibration - Point 2</div>
                        <ul class="numberBullets phInstructions">
                            <li class="phInstructionsLI">For a dual point calibration you should start with 7.0 buffer but you can adjust the buffer to
                                match what you have.
                            </li>
                            <li class="phInstructionsLI">Rinse the probe thoroughly with distilled water to clean it then flick the probe to remove the excess rinse
                                water. Do not rub or touch the probe bulb with a cloth since it can cause a static charge build up but you can place the outside 
                                of the probe on a paper towel to absorb the water droplets.
                            </li>
                            <li class="phInstructionsLI">Insert the probe in the buffer solution and move side to side to remove trapped air bubbles.</li>
                            <li class="phInstructionsLI">Click the <b>Start</b> button to continue with point 1.</li>
                        </ul>
                        <div class="probesCalContainer">
                            <div class="probesCalBox">
                            <div class="doseSettingsAmountBox" style="width:100%;">
                                <div class="probesBufferAmountLabel" id="label">Uncalibrated pH Reading</div>
                                <div class="probesBufferAmount" id="phValue">` + phValue[arrayID] +  `</div>
                            </div>
                            </div>
                            <div class="probesCalBox">
                                <div class="doseSettingsAmountBox">
                                    <div class="probesBufferAmountLabel" id="label">pH Buffer 2</div>
                                    <div class="probesBufferAmount" id="probesBufferAmount">` + round(phBuffer2,2).toFixed(2) +  `</div>
                                </div>
                                <div class="parameterButtonBox">
                                    <button id="changeBufferUp" onclick="changeBufferValue(2,0)" class="probesUpDownButton bi bi-arrow-up-short"></button></br>
                                    <button id="changeBufferDown" onclick="changeBufferValue(2,1)" class="probesUpDownButton bi bi-arrow-down-short"></button>
                                </div>
                            </div>
                        </div>
                        <button id="start1" class='button _wide' style='margin-top:10px; background-color:#d1d127;' type='button' onclick='probesPhCalibrate1()'>Start 2nd Point</button>
                    </div>
                    <div class='widgetButtonBox'>
                        <button class='button _48 back_48' style='margin-top:10px;' type='button' onclick='cancelProbeCalibration(0); probesCalibrateType(" + pHcalibratingAddress + ");'></button>
                        <button class='button _48 home_48' style='margin-top:10px;' type='button' onclick='cancelProbeCalibration(0); loadLayout();'></button>
                    </div>
                </div>`;

            document.getElementById('label').style.color = "#d1d127";  // change label color
            document.getElementById('start1').style.backgroundColor = "#d1d127";  // change button color
        }
    }

    // mouse up/down control for sensor value 
    var timer;
    var count = 0;
    var adjusted = 0;
    $('#changeBufferUp').mousedown(function () {  // action to take when mouse is down every 150ms
        timer = setInterval(function () {
            adjusted = 1;
            changeBufferValue(buffer, "0");
            count++;  // count each cycle while mouse button is down
            if (count > 10) {  // after 10 cycles increase cycle speed to 50ms
                clearInterval(timer); 
                timer = setInterval(function () {
                    changeBufferValue(buffer, "0");
                    count++;
                    if (count > 60) {  // after 60 cycles increase cycle speed to 10ms
                        clearInterval(timer);
                        timer = setInterval(function () {
                            changeBufferValue(buffer, "0");
                        }, 10);
                    }
                }, 50);
            }
        }, 150);
    }).mouseup(function () {  // stop action when mouse is up
        count = 0;
        adjusted = 0;
        // saveDoseAmount();
        clearInterval(timer);
    }).mouseout(function () {  // stop action when mouse moves off up/down button
        count = 0;
        // if (adjusted == 1) {saveDoseAmount();}
        adjusted = 0;
        clearInterval(timer);
    });

    $('#changeBufferDown').mousedown(function () {  // action to take when mouse is down every 150ms
        timer = setInterval(function () {
            adjusted = 1;
            changeBufferValue(buffer, "1");
            count++;  // count each cycle while mouse button is down
            if (count > 10) {  // after 10 cycles increase cycle speed to 50ms
                clearInterval(timer); 
                timer = setInterval(function () {
                    changeBufferValue(buffer, "1");
                    count++;
                    if (count > 60) {  // after 60 cycles increase cycle speed to 10ms
                        clearInterval(timer);
                        timer = setInterval(function () {
                            changeBufferValue(buffer, "1");
                        }, 10);
                    }
                }, 50);
            }
        }, 150);
    }).mouseup(function () {  // stop action when mouse is up
        count = 0;
        adjusted = 0;
        // saveDoseAmount();
        clearInterval(timer);
    }).mouseout(function () {  // stop action when mouse moves off up/down button
        count = 0;
        // if (adjusted == 1) {saveDoseAmount();}
        adjusted = 0;
        clearInterval(timer);
    });
}

function phVerifyCalibration() {  // verify calibration will be erased
    // console.log('phVerifyCalibration');
    for (i = 0; i < phSeen; i++) { 
        if (phAddrPlugged[i] == pHcalibratingAddress) {  // find probe being calibrated
            $('#popupBackground').show();  // grey out background
            $('.ds18b20Popup-body').empty();
            ds18b20Popup.style.display = "block";
            document.querySelector("body").style.overflow = 'hidden';
            $('.ds18b20PopupHeader').empty();
            $(".ds18b20PopupHeader").append("Calibrate pH");
        
            $(".ds18b20Popup-body").append(
                `<div style="text-align: center;"><p>&nbsp;</p>\
                    <p>Are you sure you want to calibrate the ` + phNamePlugged[i] + `?</p>\
                    <p>Clicking <b>Yes</b> will delete the current calibration.</p>\
                    <p>&nbsp;</p>\
                    <div class='widgetButtonBox' style="margin-top:0px;">\
                        <button class="button _wide" type="button" onclick="probesPhCalibrate1()">Yes</button>\
                        <button class="button _wide" type="button" onclick="probesPhCalibrate(` + calibrationTypeRunning + `)">No</button>\
                    </div>\
                    <p>&nbsp;</p>\
                </div>`);
                
            break;
        }
    }
}

function probesPhCalibrate1() {  // calibration running screen

    var bufferValue = 0;
    if (phCalibratingStep == 1) {  // point 1
        bufferValue = round(phBuffer1,2).toFixed(2);
        closeDs18b20Popup();
        var command = "34, " + pHcalibratingAddress + ",3," + round(phBuffer1,2).toFixed(2);
        sendToBackend(command);
    }
    else if (phCalibratingStep == 2) {  // point 2
        bufferValue = round(phBuffer2,2).toFixed(2);
        closeDs18b20Popup();
        var command = "34, " + pHcalibratingAddress + ",4," + round(phBuffer2,2).toFixed(2);
        sendToBackend(command);
        phCalibratingStep = 3;
    }

    var arrayID = 0;
    for (i = 0; i < phSeen; i++) { 
        if (phAddrPlugged[i] == pHcalibratingAddress) {arrayID = i; break;}
    }

    phCalibrateRunning[arrayID] = 1;  // set flag that calibration is running

    document.getElementById('content').innerHTML =
        `<div class='cleanScreen' id='cleanScreen'>
            <div class='settingsContainer' id='container'>
                <div class="settingsTitle" id="label">Waiting for pH to stabilize!</div>
                <div class="probesCalContainer">
                    <div class="probesCalStabileBox" id="probesCalStabileBox"></div>
                    <div class="probesCalNote">(carefully stir probe in buffer solution from time to time to help stabilize quicker)</div>
                </div>
                <div class="probesCalContainer">
                    <div class="probesCalBox">
                    <div class="doseSettingsAmountBox" style="width:100%;">
                        <div class="probesBufferAmountLabel" id="label">Uncalibrated pH Reading</div>
                        <div class="probesBufferAmount" id="phValue">` + phValue[arrayID] +  `</div>
                    </div>
                    </div>
                    <div class="probesCalBox">
                        <div class="doseSettingsAmountBox" style="width:100%;">
                            <div class="probesBufferAmountLabel" id="label">pH Buffer</div>
                            <div class="probesBufferAmount" id="probesBufferAmount">` + bufferValue +  `</div>
                        </div>
                    </div>
                </div>
                <div class='widgetButtonBox'>
                    <button id="start1" class='button _wide' style='margin-top:10px; background-color:#d1d127;' type='button' onclick='cancelProbeCalibration(1)'>Stop Waiting</button>
                </div>
            </div>
        </div>`;

    document.getElementById('label').style.color = "#d1d127";  // change label color
}

function updatePhStabilizeBox() {  // update stabilizing slider
    var stabilizeBoxWidth = document.getElementById('probesCalStabileBox').clientWidth;
    var tickWidth = stabilizeBoxWidth / 20;  // calculate how wide each tick box should be based on screen width

    if (phCalibrationTickCount == 0) {$('#probesCalStabileBox').empty();}  // start slider over

    if (phCalibrationTickCount > prevPhCalibrationTickCount) {  // draw new tick
        document.getElementById('probesCalStabileBox').innerHTML += 
            `<div class="stabilizeTick" id="stabilizeTick" style="width:` + tickWidth + `px"></div>`;
    }
}

function pHCalibrationFinished() {  // calibration finished screen
    displayScreen = 6;
    
    document.getElementById('content').innerHTML =
        `<div class='cleanScreen' id='cleanScreen'>
            <div class='settingsContainer' id='container'>
                <div class="settingsTitle" id="label">Congradulations you have successfully calibrated your pH probe!</div>
                <div class="probesCalNote">Detailed results will be shown in next version.</div>
            </div>
            <div class='widgetButtonBox'>
                <button class='button _48 back_48' style='margin-top:10px;' type='button' onclick='viewSettingsMenu()'></button>
                <button class='button _48 home_48' style='margin-top:10px;' type='button' onclick='loadLayout()'></button>
            </div>
        </div>`;
    
    document.getElementById('label').style.color = "#d1d127";  // change label color

    phCalibratingStep = 0;
    prevPhCalibrationTickCount = 0;
    phCalibrationTickCount = 0;
    calibrationTypeRunning = 0;
    pHcalibratingAddress = 0;
}

function phVerifyDeleteCalibration() {  // verify calibration will be erased popup
    for (i = 0; i < phSeen; i++) { 
        if (phAddrPlugged[i] == pHcalibratingAddress) {  // find probe being calibrated
            $('#popupBackground').show();  // grey out background
            $('.ds18b20Popup-body').empty();
            ds18b20Popup.style.display = "block";
            document.querySelector("body").style.overflow = 'hidden';
            $('.ds18b20PopupHeader').empty();
            $(".ds18b20PopupHeader").append("Calibrate pH");
        
            $(".ds18b20Popup-body").append(
                `<div style="text-align: center;"><p>&nbsp;</p>\
                    <p>Are you sure you want to delete the calibration for ` + phNamePlugged[i] + `?</p>\
                    <p>&nbsp;</p>\
                    <div class='widgetButtonBox' style="margin-top:0px;">\
                        <button class="button _wide" type="button" onclick="phDeleteCalibration()">Yes</button>\
                        <button class="button _wide" type="button" onclick="settingsProbes()">No</button>\
                    </div>\
                    <p>&nbsp;</p>\
                </div>`);
                
            break;
        }
    }
}

function phDeleteCalibration() {  // delete calibration
    closeDs18b20Popup();
    probesCalibrateType(pHcalibratingAddress);
    var command = "37, " + pHcalibratingAddress;
    sendToBackend(command);
}

function cancelProbeCalibration(source) {  //
    var command = "34, " + pHcalibratingAddress + ",5," + round(phBuffer1,2).toFixed(2);
    sendToBackend(command);
    phCalibrateRunning[pHcalibratingAddress] = 0;
    phCalibrationTickCount = 0;
    prevPhCalibrationTickCount = 0;
    phCalibratingStep = 0;
    if (source == 1) settingsProbes();
}

function changeBufferValue(buffer, position) {
    if (position == 0) {  // up
        if (buffer == 1) {phBuffer1 = phBuffer1 + 0.01;}  // buffer 1
        else {phBuffer2 = phBuffer2 + 0.01;}  // buffer 2
    }
    else {  // down
        if (buffer == 1) {phBuffer1 = phBuffer1 - 0.01;}  // buffer 1
        else {phBuffer2 = phBuffer2 - 0.01;}  // buffer 2
    }
    
    if (buffer == 1) {document.getElementById('probesBufferAmount').innerHTML = round(phBuffer1,2).toFixed(2);}
    else {document.getElementById('probesBufferAmount').innerHTML = round(phBuffer2,2).toFixed(2);}
}
