
var rulesNewRule = [];  // temporarily store rule data as it's being created step by step
var rulesNewRuleACPin = [];
var rulesNewRuleAC = [];
var rulesNewRuleACDelay = [];
var rulesNewRuleDCPin = [];
var rulesNewRuleDC = [];
var rulesNewRuleDCDelay = [];
var rulesNewRuleDosePin = [];
var rulesNewRuleDose = [];
var rulesNewRuleDoseDelay = [];
var rulesNewRuleDoseSuspend = [];
var rulesNewRuleDoseML = [];
// 0  = Rule Type
// 1  = Logic for second sensor
// 2  = Sensor 1 value
// 3  = Sensor 1 sensor data type
// 4  = Sensor 1 less than or greater than
// 5  = Sensor 1 stability delay
// 6  = Sensor 1 pinTypeID
// 7  = Sensor 1 pinID
// 8  = Sensor 1 sensor name
// 9  = Sensor 2 value
// 10  = Sensor 2 sensor data type
// 11  = Sensor 2 less than or greater than
// 12  = Sensor 2 stability delay
// 13  = Sensor 2 pinTypeID
// 14  = Sensor 2 pinID
// 15  = Sensor 2 sensor name
// 16  = dashboard alert
// 17  = email alert
// 18  = custom rule name


function customRulesList() {  // list of custom rules
    printHeaderTitle("CUSTOM RULES", "rules4.png");  // name and file

    removeFooter();
    
    document.getElementById('content').innerHTML +=
        "<div class='cleanScreen' id='cleanScreen'>\
            <div class='ruleMenu'>\
                <button class='button _wide' onclick='addCustomRuleMenu()'>Add Custom Rule</button>\
            </div>\
        </div>";
    
    for (var i=0; i < ruleID.length; i++) {  // go through each custom rule and print list
        document.getElementById('cleanScreen').innerHTML +=
            "<div class='rulesContainer' id='rulesContainer'>\
                <div class='settingsTitle ruleList' id='ruleList_" + i + "' onclick='expandCustomRule(" + i + ")'>"
                    + rulesName[i] + "\
                    <div class='deleteRule bi bi-trash-fill' onclick='deleteRuleConfirm(" + i + ")'></div>\
                    <div class='deleteRule bi bi-pencil-fill' onclick='editRule(" + i + ")'></div>\
                    <div class='deleteRule enableRule bi bi-toggle-on' onclick='enableRule(" + i + ")' id='enableRule_" + i + "'></div>\
                </div>\
                <div class='rulesListCol1' id='rulesListCol1_" + i + "'>\
                    <div class='rulesListCol1_Sensors' id='rulesListCol1_Sensors_" + i + "'>\
                        <div class='ruleListSensorLineBox' id='ruleListSensorLineBox_" + i + "'></div>\
                    </div>\
                    <div class='rulesListCol1_Equipment' id='rulesListCol1_Equipment_" + i + "'></div>\
                    <div class='ruleListAlertsBox' id='ruleListAlertsBox_" + i + "'></div>\
                </div>\
            </div>";

        for (var c=0; c < rulesSensorRuleID.length; c++) {  // go through all sensors, find any for this rule and print text version
            if (rulesSensorRuleID[c] == ruleID[i]) {
                var ruleText = "";
                var ruleLogicText = "";
                var ruleNameText = "";
                if ((rulesSensorPinTypeID[c] == 3) && (rulesSensorLessGreater[c] == 1)) {  // ph
                    ruleText = "is greater than " + round(rulesSensorValue[c],3);
                }
                else if ((rulesSensorPinTypeID[c] == 3) && (rulesSensorLessGreater[c] == 0)) {  // ph
                    ruleText = "is less than " + round(rulesSensorValue[c],3);
                }
                else if ((rulesSensorPinTypeID[c] == 4) && (rulesSensorLessGreater[c] == 1)) {  // DHT22
                    ruleText = "is greater than " + round(rulesSensorValue[c],1);
                    if (rulesSensorDataType[c] == 0) {ruleText += "\u00B0";}  // temperature
                    else if (rulesSensorDataType[c] == 1) {ruleText += "%";}  // humidity
                }
                else if ((rulesSensorPinTypeID[c] == 4) && (rulesSensorLessGreater[c] == 0)) {  // DHT22
                    ruleText = "is less than " + round(rulesSensorValue[c],1);
                    if (rulesSensorDataType[c] == 0) {ruleText += "\u00B0";}  // temperature
                    else if (rulesSensorDataType[c] == 1) {ruleText += "%";}  // humidity
                }
                else if ((rulesSensorPinTypeID[c] == 5) && (rulesSensorLessGreater[c] == 1)) {  // temperature
                    ruleText = "is greater than " + round(rulesSensorValue[c],1) + "\u00B0";
                }
                else if ((rulesSensorPinTypeID[c] == 5) && (rulesSensorLessGreater[c] == 0)) {  // temperature
                    ruleText = "is less than " + round(rulesSensorValue[c],1) + "\u00B0";
                }
                else if (rulesSensorPinTypeID[c] == 6) {  // non contact sensor
                    if (rulesSensorValue[c] == 1) {
                        ruleText = "is sensing water";
                    }
                    else if (rulesSensorValue[c] == 0) {
                        ruleText = "is not sensing water";
                    }
                }                
                else if (rulesSensorValue[c] == 1) {  // water sensor
                    ruleText = "is touching water";
                }
                else if (rulesSensorValue[c] == 0) {  // water sensor
                    ruleText = "is not touching water";
                }

                if (rulesSensorStability[c] > 0) {
                    ruleText += " for " + rulesSensorStability[c];
                    if (rulesSensorStability[c] == 1) {ruleText += " consecutive second";}
                    else {ruleText += " consecutive seconds";}
                }

                if ((rulesSensorPinTypeID[c] == 4) && (rulesSensorDataType[c] == 0)) {
                    ruleNameText = " Temperature"
                }
                else if ((rulesSensorPinTypeID[c] == 4) && (rulesSensorDataType[c] == 1)) {
                    ruleNameText = " Humidity"
                }

                if (rulesSensorLogic[c-1] == 1) {
                    ruleLogicText = "AND "
                }
                else if (rulesSensorLogic[c-1] == 2) {
                    ruleLogicText = " OR "
                }

                console.log(rulesSensorName[c]);
                // print text version of settings for sensor
                document.getElementById('ruleListSensorLineBox_' + i).innerHTML +=
                    "<div class='ruleListSensorLine'><span style='color:#FF0000'>" + ruleLogicText + "</span> If " + rulesSensorName[c] + ruleNameText + " " + ruleText + "</div>";
            }
        }

        if (rulesEmail[i] == 1) {  // add email enabled icon
            document.getElementById('ruleListAlertsBox_' + i).innerHTML +=
                '<div class="ruleListAlerts"><i class="bi bi-envelope-fill">&nbsp; Email Enabled</i></div>';
        }
        if (rulesAlert[i] == 1) {  // add dashboard alert enabled icon
            document.getElementById('ruleListAlertsBox_' + i).innerHTML +=
                '<div class="ruleListAlerts"><i class="bi bi-exclamation-triangle-fill">&nbsp; Dashboard Alert</i></div>';
        }

        if (rulesEnabled[i] == 1) {
            document.getElementById('ruleList_' + i).style.backgroundColor = "rgb(2, 38, 240)";  // change header color
            document.getElementById('ruleList_' + i).style.color = "#FFFFFF";  // change custom rule name color
            document.getElementById('enableRule_' + i).style.color = "#FFFFFF";  // change header color
            document.getElementById('enableRule_' + i).classList.remove('bi-toggle-off');
            document.getElementById('enableRule_' + i).classList.add('bi-toggle-on');
        }
        else {
            document.getElementById('ruleList_' + i).style.backgroundColor = "#292929";  // change header color
            document.getElementById('ruleList_' + i).style.color = "#6a6a6a";  // change custom rule name color
            document.getElementById('enableRule_' + i).style.color = "#FF0000";  // change header color
            document.getElementById('enableRule_' + i).classList.remove('bi-toggle-on');
            document.getElementById('enableRule_' + i).classList.add('bi-toggle-off');
        }

        for (var c=0; c < rulesEquipRuleID.length; c++) {  // go through all equipment and print icons
            // console.log("rulesEquipRuleID[c] = " + rulesEquipRuleID[c]);
            if (rulesEquipRuleID[c] == ruleID[i]) {
                
                var equipTitle = "";
                if (rulesEquipPinTypeID[c] == 12) {
                    equipTitle = "Dosing " + rulesEquipDoseML[c] + " mL's - ";
                }
                else if (rulesEquipOffOn[c] == 0) {equipTitle = "Turn Off "}
                else if (rulesEquipOffOn[c] == 1) {equipTitle = "Turn On "}

                if (rulesEquipPinTypeID[c] == 12) {
                    document.getElementById('rulesListCol1_Equipment_' + i).innerHTML += 
                        '<div class="ruleListEquipBox">\
                            <div class="ruleListSwitchDelay" id="">' + equipTitle + " " + rulesEquipName[c] + '</div>\
                            <img id="outletIcon_' + c + '" class="ruleListEquipIcon" src="images/Outlets/OutLD' + rulesEquipIconID[c] + 'S.png" title="' + rulesEquipName[c] + '">\
                            <div class="ruleListSwitchDelay" id="ruleListDoseML_' + c + '"></div>\
                            <div class="ruleListSwitchDelay" id="ruleListSwitchDelay_' + c + '"></div>\
                            <div class="ruleListSwitchDelay" id="rulesEquipNextDoseDelay_' + c + '"></div>\
                        </div>';
                }
                else {
                    document.getElementById('rulesListCol1_Equipment_' + i).innerHTML += 
                        '<div class="ruleListEquipBox">\
                            <div class="ruleListSwitchDelay" id="">' + equipTitle + " " + rulesEquipName[c] + '</div>\
                            <img id="outletIcon_' + c + '" class="ruleListEquipIcon" src="images/Outlets/OutLD' + rulesEquipIconID[c] + 'S.png" title="' + rulesEquipName[c] + '">\
                            <div class="ruleListSwitchDelay" id="ruleListSwitchDelay_' + c + '"></div>\
                        </div>';
                }
                    
                // if (rulesEquipPinTypeID[c] == 12) {
                //     var ruleText = "Dosing " + rulesEquipDoseML[c] + " milliliters";
                //     document.getElementById('ruleListDoseML_' + c).innerHTML = ruleText;
                // }
                var ruleText = "";
                if (rulesEquipSwitchDelay[c] == 0) {ruleText = "Switches immediately";}
                else if (rulesEquipSwitchDelay[c] > 0) {ruleText = "Switches " + rulesEquipSwitchDelay[c] + " seconds after rule starts";}                
                document.getElementById('ruleListSwitchDelay_' + c).innerHTML += ruleText;

                
                if (rulesEquipPinTypeID[c] == 12) {
                    ruleText = "";
                    if (rulesEquipNextDoseDelay[c] == 0) {  // no dose delay set in rule so grab default value
                        for (var g = 0; g < dosePinID.length; g++){
                            if (rulesEquipPinID[c] == dosePinID[g]) {
                                ruleText = "Suspend dosing for " + rulesEquipDoseML[g] + " minutes";
                                break;
                            }
                        }
                    }
                    else if (rulesEquipNextDoseDelay[c] > 0) {ruleText = "Suspend dosing for " + rulesEquipNextDoseDelay[c] + " minutes";}
                    document.getElementById('rulesEquipNextDoseDelay_' + c).innerHTML += ruleText;
                }


                if (rulesEquipOffOn[c] == 1) {document.getElementById('outletIcon_' + c).style.backgroundColor = "#00b610";}
                else {document.getElementById('outletIcon_' + c).style.backgroundColor = "#FF0000";}
            }
        }
    }

    document.getElementById('cleanScreen').innerHTML +=
        "<div class='widgetButtonBox'>\
            <button class='button _48 home_48' style='margin-top:40px;' type='button' onclick='loadLayout()'></button>\
        </div>";
}

function addCustomRuleMenu() {  // main menu for adding custom rule, schedule, sensor or manual
    console.log("addCustomRuleMenu -------------- ");
    
    for (var c=0; c < 19; c++) {  // 
        rulesNewRule[c] = 255; // reset array
    }

    // CODE BELOW IS A MENU FOR RULE TRIGGER WHICH CAN BE SCHEDULE, SENSOR OR MANUAL ------------------------------------------------------
    // ----------------------------------------------------------------------------------------------------------------------
    // $('#cleanScreen').empty();  // empty window

    // document.getElementById('cleanScreen').innerHTML +=
    //     "<div class='rulesContainer' id='rulesContainer'></div>";

    // document.getElementById('rulesContainer').innerHTML +=  // 
    //     '<div class="settingsTitle">How do you want to trigger the custom rule?</div>\
    //     <div class="ruleOptionContainer">\
    //         <div class="menuBox">\
    //             <div class="menuIcon" id="ruleSchedule" onclick="addCustomRule2(0,0,0)"></div>\
    //             <div class="menuIconName" onclick="addCustomRule2(0,0,0)">Schedule</div>\
    //         </div>\
    //         <div class="menuBox">\
    //             <div class="menuIcon" id="ruleSensor" onclick="addSensorRule(0,0)"></div>\
    //             <div class="menuIconName" onclick="addSensorRule(0,0)">Sensor</div>\
    //         </div>\
    //         <div class="menuBox">\
    //             <div class="menuIcon bootstrapIcon bi bi-hand-index-thumb-fill" id="ruleManual" onclick="addCustomRule2(2,0,0)"></div>\
    //             <div class="menuIconName" onclick="addCustomRule2(2,0,0)">Manually</div>\
    //         </div>\
    //     </div>\
    //     <div class="widgetButtonBox">\
    //         <button class="button _wide" type="button" onclick="customRulesList()">Cancel</button>\
    //     </div>';
        
    // document.getElementById('ruleSchedule').style.backgroundImage = "url('/images/icons/schedules.png')";
    // document.getElementById('ruleSensor').style.backgroundImage = "url('/images/icons/sensors.png')";

    addSensorRule(0,0);  // temporary using this to go straight to sensor based custom rule
}

function addCustomRule2(type, sensorNumber, logic) {  // NOT USING RIGHT NOW -- add rule step 2, setup schedule or manual
    // console.log("addCustomRule2 -------------- ");
    // console.log("type = " + type);
    rulesNewRule[0] = type; // store rule type to save later
    rulesNewRule[1] = logic; // store 2nd sensor logic to save later

    if (sensorNumber == 0) {
        $('#cleanScreen').empty();  // empty window
        document.getElementById('cleanScreen').innerHTML +=
            '<div class="rulesContainer" id="rulesContainer">\
                <div id="rulesContainerStep0"></div>\
                <div id="rulesContainerStep1"></div>\
                <div id="rulesContainerStep2"></div>\
                <div id="rulesContainerStep3"></div>\
                <div id="rulesContainerStep4"></div>\
            </div>';
    }
    else {  // setup 
        $('#rulesContainerStep2').empty();  // 
        $('#rulesContainerStep3').empty();  // 
        $('#rulesContainerStep4').empty();  // 

        document.getElementById('logic1').style.backgroundColor = "#000";
        document.getElementById('logic2').style.backgroundColor = "#000";
    
        if (logic == 1) {document.getElementById('logic1').style.backgroundColor = "rgba(0, 182, 16, 0.8)";}  // 
        else {document.getElementById('logic2').style.backgroundColor = "rgba(0, 182, 16, 0.8)";}  // 
    }

    if (type == 0) {  // print schedule form
        document.getElementById('rulesContainerBox').innerHTML +=  // 
            '<div class="rulesTitle">Setup a schedule for this custom rule!</div>';
            // addSchedule3(1);
    }
    else if (type == 2) {
        addCustomRule2a();
        // return;  // exit function
    }

    if (sensorNumber == 0) {
        document.getElementById('rulesContainer').innerHTML +=  // 
            '<div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="customRulesList()">Cancel</button>\
            </div>';
    }
}

function addSensorRule(sensorNumber, logic) {  // setup drop down list of sensors
    // console.log("addSensorRule -------------- ");
    rulesNewRule[0] = 2; // store rule type to save later
    rulesNewRule[1] = logic; // store 2nd sensor logic to save later

    if (sensorNumber == 0) {  // draw main template but only for sensor 1
        $('#cleanScreen').empty();  // empty window
        document.getElementById('cleanScreen').innerHTML +=
            '<div class="rulesContainer" id="rulesContainer">\
                <div id="rulesContainerStep0"></div>\
                <div id="rulesContainerStep1"></div>\
                <div id="rulesContainerStep2"></div>\
                <div id="rulesContainerStep3"></div>\
                <div id="rulesContainerStep4"></div>\
            </div>';
    }
    else {  // setup page to setup sensor 2
        $('#rulesContainerStep2').empty();  // 
        $('#rulesContainerStep3').empty();  // 
        $('#rulesContainerStep4').empty();  // 

        document.getElementById('logic1').style.backgroundColor = "#000";  // format AND logic button
        document.getElementById('logic2').style.backgroundColor = "#000";  // format OR logic button
    
        if (logic == 1) {document.getElementById('logic1').style.backgroundColor = "rgba(0, 182, 16, 0.8)";}  // format AND logic button
        else {document.getElementById('logic2').style.backgroundColor = "rgba(0, 182, 16, 0.8)";}  // format OR logic button
    }

    // draw step 1 - sensor drop down
    document.getElementById('rulesContainerStep1').innerHTML =  //
        '<div class="rulesTitle">What sensor would you like to use?</div>\
        <div class="ruleOptionBox" id="ruleOptionBox" style="padding-bottom:20px;"></div>';

    document.getElementById('ruleOptionBox').innerHTML +=  // draw drop down box 
        '<select class="field" id="ruleSensorsSelect" onchange="addSensorRuleStep2(' + sensorNumber + ')">\
            <option value="0"></option>\
            <option class="selectTitles" value="" disabled>Water Sensors</option>\
        </select>';
    
    var count = 2;  // used to count each option in drop down list
    var remove = 0;  // used to track which sensor to remove from drop down list after creating it
    for (var i=0; i < sensorPinID.length; i++)  // add water sensors to drop down list
    {
        document.getElementById('ruleSensorsSelect').innerHTML +=  // 
            '<option value="' + sensorPinID[i] + '">' + sensorName[i] + '</option>';
        
        if ((sensorNumber == 1) && (sensorName[i] == rulesNewRule[8])) {remove = count;}  // mark sensor to remove from drop down if used as 1st sensor
        count++;  // count option
    }

    count++;  // count option
    document.getElementById('ruleSensorsSelect').innerHTML +=  // add title for temperature sensors
        '<option class="selectTitles" value="" disabled>Temperature Sensors</option>';
    
    for (var i=0; i < ds18b20NamePlugged.length; i++)  // add temp sensors to drop down list
    {
        if (ds18b20AddrFound[i].includes("dht")) {  // search for DTH22 and add Temperature to custom name
            if ((sensorNumber == 1) && (rulesNewRule[8].includes("Temperature"))) {remove = count;}  // mark sensor to remove from drop down if used as 1st sensor
            count++;  // count option

            document.getElementById('ruleSensorsSelect').innerHTML +=  // 
                '<option value="' + ds18b20AddrFound[i] + '">' + ds18b20NamePlugged[i] + ' - Temperature</option>';
                
            if ((sensorNumber == 1) && (rulesNewRule[8].includes("Humidity"))) {remove = count;}  // mark sensor to remove from drop down if used as 1st sensor
            count++;  // count option

            document.getElementById('ruleSensorsSelect').innerHTML +=  // 
                '<option value="' + ds18b20AddrFound[i] + '">' + ds18b20NamePlugged[i] + ' - Humidity</option>';
        }
        else {  // DS18B20's
            if ((remove == 0) && (sensorNumber == 1) && (rulesNewRule[8].includes(ds18b20NamePlugged[i]))) {remove = count;}  // mark sensor to remove from drop down if used as 1st sensor
            count++;  // count option
            document.getElementById('ruleSensorsSelect').innerHTML +=  // 
                '<option value="' + ds18b20AddrFound[i] + '">' + ds18b20NamePlugged[i] + '</option>';
        }
    }
    
    count++;  // count option
    document.getElementById('ruleSensorsSelect').innerHTML +=  // add title for pH probes
        '<option class="selectTitles" value="" disabled>pH Probes</option>';

    for (var i=0; i < phNamePlugged.length; i++)  // add pH sensors to drop down list
    {
        if ((sensorNumber == 1) && (rulesNewRule[8].includes(phNamePlugged[i]))) {remove = count;}  // mark sensor to remove from drop down if used as 1st sensor
        count++;  // count option

        document.getElementById('ruleSensorsSelect').innerHTML +=  // 
            '<option value="pH_' + phAddrPlugged + '">' + phNamePlugged[i] + '</option>';
    }

    if (sensorNumber == 0) {  // if loading sensor 1 draw the cancel button
        document.getElementById('rulesContainer').innerHTML +=  // 
            '<div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="customRulesList()">Cancel</button>\
            </div>';
    }
    else {  // remove 1st sensor used from drop down list
        var dropdown = document.getElementById("ruleSensorsSelect");
        dropdown.remove(remove);
    }
}

function addSensorRuleStep2(sensorNumber) {  // setup sensor value
    console.log("-");
    console.log("addSensorRuleStep2 -------------- ");
    var sensorID = document.getElementById('ruleSensorsSelect').value;  // get sensor pin / address from dropdown so we know what sensor is
    console.log("sensorID = " + sensorID);

    var sensorValue = 0;  // used temporary to change sensor value

    $('#rulesContainerStep2').empty();  // 
    $('#rulesContainerStep3').empty();  // 
    $('#rulesContainerStep4').empty();  // 
    
    document.getElementById('rulesContainerStep2').innerHTML =  // 
        '<div class="ruleOptionBox" id="ruleOptionBox2"></div>';

    if (isThisANumber(sensorID)) {  // layout for water sensors
        var arrayID = 0;
        for (var i=0; i < sensorPinID.length; i++)  // search for sensorPinID so we can find what type of sensor it is.
        {
            if (sensorID == sensorPinID[i]) {arrayID = i; break;}
        }
        
        var customName = getSensorOptionText('ruleSensorsSelect');  // get custom name from sensor drop down box

        if (sensorNumber == 0) {  // update settings for Sensor 1
            rulesNewRule[3] = 0;  // sensor data type
            rulesNewRule[4] = 0;  // less than or greater than
            rulesNewRule[8] = customName;  // sensor name
        }
        else {  // update settings for Sensor 2
            rulesNewRule[10] = 0;  // sensor data type
            rulesNewRule[11] = 0;  // less than or greater than
            rulesNewRule[15] = customName;  // sensor name
        }

        if (sensorTypeID[arrayID] == 6) {  // non-contact sensor
            if (sensorNumber == 0) {rulesNewRule[6] = 6; rulesNewRule[7] = sensorPinID[arrayID];}  // update pinTypeID for sensor 1
            else {rulesNewRule[13] = 6; rulesNewRule[14] = sensorPinID[arrayID];}  // update pinTypeID for sensor 2

            document.getElementById('ruleOptionBox2').innerHTML =  // 
                '<div class="rulesTitle">What position should the non-contact sensor be in to trigger the custom rule?</div>\
                <div class="ruleOptionContainer" id="ruleSensorOptionBox"></div>';

            document.getElementById('ruleSensorOptionBox').innerHTML +=  // 
                '<div class="ruleSensorOptionBox" id="option0" onclick="addSensorRuleStep3(1,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/non-contact1.png">\
                    </br>Sensing Water\
                </div>\
                <div class="ruleSensorOptionBox" id="option1" onclick="addSensorRuleStep3(0,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/non-contact2.png">\
                    </br>Not Sensing Water\
                </div>';
        }
        else if (sensorTypeID[arrayID] == 7) {  // optical sensor
            if (sensorNumber == 0) {rulesNewRule[6] = 7; rulesNewRule[7] = sensorPinID[arrayID];}  // update pinTypeID for sensor 1
            else {rulesNewRule[13] = 7; rulesNewRule[14] = sensorPinID[arrayID];}  // update pinTypeID for sensor 2
            
            document.getElementById('ruleOptionBox2').innerHTML =  // 
                '<div class="rulesTitle">What position should the optical sensor be in to trigger the custom rule?</div>\
                <div class="ruleOptionContainer" id="ruleSensorOptionBox"></div>';

            document.getElementById('ruleSensorOptionBox').innerHTML +=  // 
                '<div class="ruleSensorOptionBox" id="option0" onclick="addSensorRuleStep3(1,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/optical_down.png">\
                    </br>Touching Water\
                </div>\
                <div class="ruleSensorOptionBox" id="option1" onclick="addSensorRuleStep3(0,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/optical_up.png">\
                    </br>Not Touching Water\
                </div>';
        }
        else if (sensorTypeID[arrayID] == 8) {  // float switch
            if (sensorNumber == 0) {rulesNewRule[6] = 8; rulesNewRule[7] = sensorPinID[arrayID];}  // update pinTypeID for sensor 1
            else {rulesNewRule[13] = 8; rulesNewRule[14] = sensorPinID[arrayID];}  // update pinTypeID for sensor 2
            
            document.getElementById('ruleOptionBox2').innerHTML =  // 
                '<div class="rulesTitle">What position should the float switch be in to trigger the custom rule?</div>\
                <div class="ruleOptionContainer" id="ruleSensorOptionBox"></div>';

            document.getElementById('ruleSensorOptionBox').innerHTML +=  // 
                '<div class="ruleSensorOptionBox" id="option0" onclick="addSensorRuleStep3(1,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/float_up.png">\
                    </br>Touching Water\
                </div>\
                <div class="ruleSensorOptionBox" id="option1" onclick="addSensorRuleStep3(0,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/float_down.png">\
                    </br>Not Touching Water\
                </div>';
        }
        else if (sensorTypeID[arrayID] == 9) {  // other sensor
            if (sensorNumber == 0) {rulesNewRule[6] = 9; rulesNewRule[7] = sensorPinID[arrayID];}  // update pinTypeID for sensor 1
            else {rulesNewRule[13] = 9; rulesNewRule[14] = sensorPinID[arrayID];}  // update pinTypeID for sensor 2
            
            document.getElementById('ruleOptionBox2').innerHTML =  // 
                '<div class="rulesTitle">What position should the sensor be in to trigger the custom rule?</div>\
                <div class="ruleOptionContainer" id="ruleSensorOptionBox"></div>';

            document.getElementById('ruleSensorOptionBox').innerHTML +=  // 
                '<div class="ruleSensorOptionBox" id="option0" onclick="addSensorRuleStep3(1,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/other_sensor1.png">\
                    </br>Touching Water\
                </div>\
                <div class="ruleSensorOptionBox" id="option1" onclick="addSensorRuleStep3(0,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/other_sensor2.png">\
                    </br>Not Touching Water\
                </div>';
        }
        else if (sensorTypeID[arrayID] == 14) {  // toggle switch
            if (sensorNumber == 0) {rulesNewRule[6] = 14; rulesNewRule[7] = sensorPinID[arrayID];}  // update pinTypeID for sensor 1
            else {rulesNewRule[13] = 14; rulesNewRule[14] = sensorPinID[arrayID];}  // update pinTypeID for sensor 2
            
            document.getElementById('ruleOptionBox2').innerHTML =  // 
                '<div class="rulesTitle">What position should the toggle switch be in to trigger the custom rule?</div>\
                <div class="ruleOptionContainer" id="ruleSensorOptionBox"></div>';

            document.getElementById('ruleSensorOptionBox').innerHTML +=  // 
                '<div class="ruleSensorOptionBox" id="option0" onclick="addSensorRuleStep3(1,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/toggle_on.png">\
                    </br>On\
                </div>\
                <div class="ruleSensorOptionBox" id="option1" onclick="addSensorRuleStep3(0,' + sensorNumber + ')">\
                    <img style="padding-bottom: 10px;" src="images/icons/toggle_off.png">\
                    </br>Off\
                </div>';
        }

        $('#option0').mousedown(function () {  // used to update less than / greater than when clicked
            if (sensorNumber == 0) {  // sensor 1
                // if (rulesNewRule[4] == 0) {  // less than
                //     rulesNewRule[4] = 1;
                // } 
                // else {  // greater than
                    rulesNewRule[4] = 0;
                // }
            }
            else {  // sensor 2
                // if (rulesNewRule[11] == 0) {  // less than
                //     rulesNewRule[11] = 1;
                // } 
                // else {  // greater than
                    rulesNewRule[11] = 0;
                // }
            }
        });

        $('#option1').mousedown(function () {  // used to update less than / greater than when clicked
            if (sensorNumber == 0) {  // sensor 1
                    rulesNewRule[4] = 1;
            }
            else {  // sensor 2
                    rulesNewRule[11] = 1;
            }
        });
    }
    else if (sensorID.includes("pH")) {  // layout for pH sensors
        var arrayID = 0;  // array location of temperature sensor from it's variable set
        for (var i=0; i < phAddrPlugged.length; i++)  // find temp sensor selected so we can use live temperatures as defaults
        {
            if (sensorID.includes(phAddrPlugged[i])) {arrayID = i; break;}
        }

        var customName = getSensorOptionText('ruleSensorsSelect');        
        if (sensorNumber == 0) {  // update settings for Sensor 1
            rulesNewRule[4] = 0;  // less than or greater than
            rulesNewRule[7] = phAddrPlugged[arrayID];  // pinID
            rulesNewRule[6] = 3;  // pinTypeID
            rulesNewRule[8] = customName;  // sensor name
            
        }
        else {  // update settings for Sensor 2
            rulesNewRule[11] = 0;  // less than or greater than
            rulesNewRule[14] = phAddrPlugged[arrayID];  // pinID
            rulesNewRule[13] = 3;  // pinTypeID
            rulesNewRule[15] = customName;  // sensor name
        }

        if (sensorNumber == 0) {rulesNewRule[2] = round(phValue[arrayID],2); sensorValue = rulesNewRule[2];}  // update sensor value for sensor 1
        else {rulesNewRule[9] = round(phValue[arrayID],2); sensorValue = rulesNewRule[9];}  // update sensor value for sensor 2        
    }
    else {  // layout for temperature sensors
        
        console.log("layout for temperature sensors");
        var arrayID = 0;  // array location of temperature sensor from it's variable set
        for (var i=0; i < ds18b20AddrFound.length; i++)  // find temp sensor selected so we can use live temperatures as defaults
        {
            if (sensorID == ds18b20AddrFound[i]) {arrayID = i; break;}
        }

        var customName = getSensorOptionText('ruleSensorsSelect');   // get custom name from sensor drop down box

        if (sensorNumber == 0) {rulesNewRule[8] = customName;}  // update custom name for Sensor 1
        else {rulesNewRule[15] = customName;}  // update custom name for Sensor 2

        // update sensor settings
        if (ds18b20AddrFound[arrayID].includes("dht")) {  // DHT22
            if (sensorNumber == 0) {rulesNewRule[6] = 4; rulesNewRule[7] = ds18b20AddrFound[arrayID];}  // pinTypeID
            else {rulesNewRule[13] = 4; rulesNewRule[14] = ds18b20AddrFound[arrayID];}  // pinTypeID
        }
        else {  // DS18B20
            if (sensorNumber == 0) {rulesNewRule[6] = 5; rulesNewRule[7] = ds18b20AddrFound[arrayID];}  // pinTypeID
            else {rulesNewRule[13] = 5; rulesNewRule[14] = ds18b20AddrFound[arrayID];}  // pinTypeID
        }

        var text = getSensorOptionText('ruleSensorsSelect');  // get sensor name from sensor drop down so we can see if it's for humidity

        if (text.includes('Humidity')) {  
            if (sensorNumber == 0) {rulesNewRule[2] = round(ds18b20Humidity[arrayID],1); sensorValue = rulesNewRule[2];}  // update sensor value for sensor 1
            else {rulesNewRule[9] = round(ds18b20Humidity[arrayID],1); sensorValue = rulesNewRule[9];}  // update sensor value for sensor 2

            if (sensorNumber == 0) {rulesNewRule[3] = 1;}  // update sensor data type for sensor 1
            else {rulesNewRule[10] = 1;}  // update sensor data type for sensor 2
        }
        else {
            if (sensorNumber == 0) {rulesNewRule[2] = round(ds18b20Temp[arrayID],1); sensorValue = rulesNewRule[2];}  // update sensor value for sensor 1
            else {rulesNewRule[9] = round(ds18b20Temp[arrayID],1); sensorValue = rulesNewRule[9];}  // update sensor value for sensor 2

            if (sensorNumber == 0) {rulesNewRule[3] = 0;}  // update sensor data type for sensor 1
            else {rulesNewRule[10] = 0;}  // update sensor data type for sensor 2
        }
    }

    var decimals = 0;  // track how many decimals the sensor value has so it can be adjusted accordingly
    console.log("sensorID 2 = " + sensorID.length);
    // sensorID = "00000b90e26a";
    // sensorID = "030e97942064";
    // if (sensorID.length
    // let isnum = /^\d+$/.test(sensorID);
    // console.log("isnum = " + isnum);
    // if (!isnum) {
    if (!isThisANumber(sensorID)) {  // finish loading step 2 for anything but water sensors
        // else {
        console.log("finish loading step 2 for anything but water sensors");
        var parameterLabel = "";  // used to print correct label when adjusting sensor value

        if (sensorID.includes("pH")) {parameterLabel = "pH"; decimals = 2;}
        else {
            decimals = 1;
            if (sensorNumber == 0) {  // sensor 1
                if (rulesNewRule[3] == 0) {parameterLabel = "Temperature";}  // get label for sensor value type
                if (rulesNewRule[3] == 1) {parameterLabel = "Humidity";}  // get label for sensor value type
            }
            else {  // sensor 2
                if (rulesNewRule[10] == 0) {parameterLabel = "Temperature";}  // get label for sensor value type
                if (rulesNewRule[10] == 1) {parameterLabel = "Humidity";}  // get label for sensor value type
            }
        }

        document.getElementById('ruleOptionBox2').innerHTML =  // 
            '<div class="rulesTitle">Set the ' + parameterLabel + ' level to trigger the custom rule.</div>\
            <div class="ruleOptionContainer" id="ruleSensorOptionBox"></div>';

        document.getElementById('ruleSensorOptionBox').innerHTML +=  // 
            '<div class="ruleSensorOptionContainer" id="ruleSensorOptionContainer">\
                <div class="ruleGreaterLabel">(click to change)</div>\
                <div id="ruleGreaterIconBox"></div>\
            </div>\
            <div class="parameterBox ruleSensorValueBox">\
                <div class="parameterInfoBox">\
                    <div class="parameterTitle">' + parameterLabel + '</div>\
                    <div class="parameterValue" id="sensorValue">' + sensorValue + '</div>\
                </div>\
                <div class="parameterButtonBox">\
                    <button id="valueButtonUp" onmousedown="ruleSensorValueUp(' + decimals + ',' + sensorNumber + ')" class="upDownButton bi bi-arrow-up-short"></button></br>\
                    <button id="valueButtonDown" onmousedown="ruleSensorValueDown(' + decimals + ',' + sensorNumber + ')" class="upDownButton bi bi-arrow-down-short"></button>\
                </div>\
            </div>';

        if (sensorNumber == 0) {rulesNewRule[4] = 0;}  // update less than or greater than for sensor 1
        else {rulesNewRule[11] = 0;}  // update less than or greater than for sensor 2
        
        document.getElementById('ruleGreaterIconBox').innerHTML =  // 
            '<img src="images/icons/lessThan.png">\
            </br>Less Than or Equal To';
        
        document.getElementById('ruleOptionBox2').innerHTML +=  // draw next step button
            '<div class="ruleSensorOptionBox" id="rulesOpenDelay" style="background-color:#00b610;">\
                Next\
            </div>';

        $('#rulesOpenDelay').mousedown(function () {  // hides next step button after being pressed
            document.getElementById('rulesOpenDelay').style.display = "none";
            addSensorRuleStep3(sensorValue, sensorNumber);
        });

        $('#ruleSensorOptionContainer').mousedown(function () {  // used to update less than / greater than when clicked
            if (sensorNumber == 0) {  // sensor 1
                if (rulesNewRule[4] == 0) {  // less than
                    rulesNewRule[4] = 1;
                    document.getElementById('ruleGreaterIconBox').innerHTML =  // 
                        '<img src="images/icons/greaterThan.png">\
                        </br>Greater Than or Equal To';
                } 
                else {  // greater than
                    rulesNewRule[4] = 0;
                    document.getElementById('ruleGreaterIconBox').innerHTML =  // 
                        '<img src="images/icons/lessThan.png">\
                        </br>Less Than or Equal To';
                }
            }
            else {  // sensor 2
                if (rulesNewRule[11] == 0) {  // less than
                    rulesNewRule[11] = 1;
                    document.getElementById('ruleGreaterIconBox').innerHTML =  // 
                        '<img src="images/icons/greaterThan.png">\
                        </br>Greater Than or Equal To';
                } 
                else {  // greater than
                    rulesNewRule[11] = 0;
                    document.getElementById('ruleGreaterIconBox').innerHTML =  // 
                        '<img src="images/icons/lessThan.png">\
                        </br>Less Than or Equal To';
                }
            }
        });
    }
    
    // mouse up/down control for sensor value 
    var timer;
    var count = 0;
    var adjusted = 0;
    $('#valueButtonUp').mousedown(function () {  // action to take when mouse is down every 150ms
        timer = setInterval(function () {
            adjusted = 1;
            ruleSensorValueUp(decimals, sensorNumber);
            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 () {
                    ruleSensorValueUp(decimals, sensorNumber);
                    count++;
                    if (count > 60) {  // after 60 cycles increase cycle speed to 10ms
                        clearInterval(timer);
                        timer = setInterval(function () {
                            ruleSensorValueUp(decimals, sensorNumber);
                        }, 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);
    });

    $('#valueButtonDown').mousedown(function () {  // action to take when mouse is down every 150ms
        timer = setInterval(function () {
            adjusted = 1;
            ruleSensorValueDown(decimals, sensorNumber);
            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 () {
                    ruleSensorValueDown(decimals, sensorNumber);
                    count++;
                    if (count > 60) {  // after 60 cycles increase cycle speed to 10ms
                        clearInterval(timer);
                        timer = setInterval(function () {
                            ruleSensorValueDown(decimals, sensorNumber);
                        }, 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 addSensorRuleStep3(value, sensorNumber) {  // setup sensor delay
    // console.log("addSensorRuleStep3 -------------- ");

    if (sensorNumber == 0) {rulesNewRule[5] = 1;}  // track sensor stabiility delay for sensor 1
    else {rulesNewRule[12] = 1;}  // track sensor stabiility delay for sensor 2
    
    var sensorID = document.getElementById('ruleSensorsSelect').value;  // get sensor pin / address from dropdown so we know what sensor is

    var text = "";  // used to customize text to be displayed

    if (isThisANumber(sensorID)) {  // layout for water sensor
        document.getElementById('option0').style.backgroundColor = "#000";  // set background for sensor level button for sensor 1
        document.getElementById('option1').style.backgroundColor = "#000";  // set background for sensor level button for sensor 2

        if (value == 1) {document.getElementById('option0').style.backgroundColor = "rgba(0, 182, 16, 0.8)";}  // set background for sensor level button for sensor 1
        else {document.getElementById('option1').style.backgroundColor = "rgba(0, 182, 16, 0.8)";}  // set background for sensor level button for sensor 2

        if (sensorNumber == 0) {  // sensor 1
            rulesNewRule[2] = value; // update sensor value
            if (rulesNewRule[6] == 6) {text = "the non-contact sensor hold it's state before ";}  // non-contact sensor
            else if (rulesNewRule[6] == 7) {text = "the optical sensor hold it's state before ";}  // optical sensor
            else if (rulesNewRule[6] == 8) {text = "the float switch hold it's state before ";}  // float switch
            else if (rulesNewRule[6] == 9) {text = "the sensor hold it's state before ";}  // other sensor
            else if (rulesNewRule[6] == 14) {text = "the toggle switch hold it's state before ";}  // toggle switch
        }
        else {  // sensor 2
            rulesNewRule[9] = value; // update sensor value
            if (rulesNewRule[13] == 6) {text = "the non-contact sensor hold it's state before ";}  // non-contact sensor
            else if (rulesNewRule[13] == 7) {text = "the optical sensor hold it's state before ";}  // optical sensor
            else if (rulesNewRule[13] == 8) {text = "the float switch hold it's state before ";}  // float switch
            else if (rulesNewRule[13] == 9) {text = "the sensor hold it's state before ";}  // other sensor
            else if (rulesNewRule[13] == 14) {text = "the toggle switch hold it's state before ";}  // toggle switch
        }
    }
    else if (sensorID.includes("pH")) {  // layout for pH sensors
        text = "the pH hold it's value before ";
    }
    else {  // layout for temperature sensors
        if (rulesNewRule[3] == 0) {text = "the temperature hold it's value before ";}  // temperature
        else {text = "the humidity hold it's value before ";}  // humidity
    }

    document.getElementById('rulesContainerStep3').innerHTML =  // 
        '<div class="ruleOptionBox" id="ruleOptionBox3"></div>';
    
    var stabilityDelay = 0;  // used to display sensor delay for correct sensor
    if (sensorNumber == 0) {stabilityDelay = rulesNewRule[5];}  // sensor 1
    else {stabilityDelay = rulesNewRule[12];}  // sensor 2

    document.getElementById('ruleOptionBox3').innerHTML =  // 
    '<div class="rulesTitle">How long should ' + text + 'triggering the custom rule?\
    </div>\
    <div class="ruleOptionContainer" id="ruleSensorDelay">\
        <div class="parameterBox">\
            <div class="parameterInfoBox">\
                <div class="parameterTitle">Seconds</div>\
                <div class="parameterValue" id="delaySeconds">' + stabilityDelay + '</div>\
            </div>\
            <div class="parameterButtonBox">\
                <button id="delayButtonUp" onmousedown="ruleSensorDelayUp(' + sensorNumber + ')" class="upDownButton bi bi-arrow-up-short"></button></br>\
                <button id="delayButtonDown" onmousedown="ruleSensorDelayDown(' + sensorNumber + ')" class="upDownButton bi bi-arrow-down-short"></button>\
            </div>\
        </div>\
        <span style="font-size:14px; color:#FFF; width:100%; margin-top:-16px;">(1 or more seconds is recommended)</span>\
    </div>';

    if (sensorNumber == 0) {
        document.getElementById('rulesContainerStep4').innerHTML =  // 
            '<div class="ruleOptionBox" id="ruleOptionBox3">\
                <div class="rulesTitle">Would you like to use a 2nd sensor for this rule?</div>\
                <div class="ruleSensorOptionBox" id="option0" onclick="addRuleEquipment()">\
                No</div>\
                <div class="ruleSensorOptionBox" id="option0" onclick="addRule2ndSensor()">\
                Yes</div>\
            </div>';
    }
    else {
        document.getElementById('rulesContainerStep4').innerHTML =  // 
            '<div class="ruleOptionBox" id="ruleOptionBox3">\
                <div class="ruleSensorOptionBox" id="option0" style="width:60%" onclick="addRuleEquipment()">\
                Click to select equipment to control.</div>\
            </div>';
    }

    // track mouse up/down when changing sensor delay    
    var timer;
    var count = 0;
    var adjusted = 0;
    $('#delayButtonUp').mousedown(function () {  // action to take when mouse is down every 150ms
        timer = setInterval(function () {
            adjusted = 1;
            ruleSensorDelayUp(sensorNumber);
            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 () {
                    ruleSensorDelayUp(sensorNumber);
                    count++;
                    if (count > 60) {  // after 60 cycles increase cycle speed to 10ms
                        clearInterval(timer);
                        timer = setInterval(function () {
                            ruleSensorDelayUp(sensorNumber);
                        }, 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);
    });

    $('#delayButtonDown').mousedown(function () {  // action to take when mouse is down every 150ms
        timer = setInterval(function () {
            adjusted = 1;
            ruleSensorDelayDown(sensorNumber);
            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 () {
                    ruleSensorDelayDown(sensorNumber);
                    count++;
                    if (count > 60) {  // after 60 cycles increase cycle speed to 10ms
                        clearInterval(timer);
                        timer = setInterval(function () {
                            ruleSensorDelayDown(sensorNumber);
                        }, 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);
    });

    // console.log("rulesNewRule[4] less/g       = " + rulesNewRule[4]);
    // console.log("rulesNewRule[2] value        = " + rulesNewRule[2]);
}

function addRule2ndSensor() {  // add 2nd sensor to custom rule
    // console.log("addRule2ndSensor -------------- ");

    $('#rulesContainerStep1').empty();  // 
    $('#rulesContainerStep2').empty();  // 
    $('#rulesContainerStep3').empty();  // 
    $('#rulesContainerStep4').empty();  // 

    // for (var c=0; c < rulesNewRule.length; c++) {  // 
    //     console.log("rulesNewRule[" + c + "] = " + rulesNewRule[c] + ", ");
    // }

    // assemble text version of first sensor options
    var ruleText = "";
    if ((rulesNewRule[6] == 3) && (rulesNewRule[4] == 1)) {  // ph
        ruleText = "is greater than " + rulesNewRule[2];
    }
    else if ((rulesNewRule[6] == 3) && (rulesNewRule[4] == 0)) {  // ph
        ruleText = "is less than " + rulesNewRule[2];
    }
    else if ((rulesNewRule[6] == 4) && (rulesNewRule[4] == 1)) {
        ruleText = "is greater than " + rulesNewRule[2];
        if (rulesNewRule[3] == 0) {ruleText += "\u00B0";}
        else if (rulesNewRule[3] == 1) {ruleText += "%";}
    }
    else if ((rulesNewRule[6] == 4) && (rulesNewRule[4] == 0)) {
        ruleText = "is less than " + rulesNewRule[2];
        if (rulesNewRule[3] == 0) {ruleText += "\u00B0";}
        else if (rulesNewRule[3] == 1) {ruleText += "%";}
    }
    else if ((rulesNewRule[6] == 5) && (rulesNewRule[4] == 1)) {  // temperature
        ruleText = "is greater than " + rulesNewRule[2] + "\u00B0";
    }
    else if ((rulesNewRule[6] == 5) && (rulesNewRule[4] == 0)) {  // temperature
        ruleText = "is less than " + rulesNewRule[2] + "\u00B0";
    }
    else if (rulesNewRule[6] == 14) {  // toggle switch
        if (rulesNewRule[2] == 1) {
            ruleText = "is on";
        }
        else if (rulesNewRule[2] == 0) {
            ruleText = "is off";
        }
    }
    else if (rulesNewRule[6] == 6) {  // non contact sensor
        if (rulesNewRule[2] == 1) {
            ruleText = "is sensing water";
        }
        else if (rulesNewRule[2] == 0) {
            ruleText = "is not sensing water";
        }
    }
    else if (rulesNewRule[2] == 1) {
        ruleText = "is touching water";
    }
    else if (rulesNewRule[2] == 0) {
        ruleText = "is not touching water";
    }

    if (rulesNewRule[5] > 0) {
        ruleText += " for " + rulesNewRule[5];
        if (rulesNewRule[5] == 1) {ruleText += " consecutive second";}
        else {ruleText += " consecutive seconds";}
    }
    
    document.getElementById('rulesContainerStep0').innerHTML =  // add text version of rule and logic buttons AND OR
        '<div class="ruleOptionBox" id="">\
            <div class="rulesTitle">If ' + rulesNewRule[8] + ' ' + ruleText + '</div>\
            <div class="ruleSensorOptionBox" id="logic1" onclick="addSensorRule(1,1)">\
            AND</div>\
            <div class="ruleSensorOptionBox" id="logic2" onclick="addSensorRule(1,2)">\
            OR</div>\
        </div>';
}

function ruleSensorDelayUp(sensorNumber) {  // adjust sensor stability delay up
    // console.log('ruleSensorDelayUp     = ' + type);
    if (sensorNumber == 0) {  // sensor 1
        rulesNewRule[5]++;
        document.getElementById('delaySeconds').innerHTML = rulesNewRule[5];
    }
    else {  // sensor 2
        rulesNewRule[12]++;
        document.getElementById('delaySeconds').innerHTML = rulesNewRule[12];
    }
}

function ruleSensorDelayDown(sensorNumber) {  // adjust sensor stability delay down
    // console.log('ruleSensorDelayDown   = ' + type); 
    if (sensorNumber == 0) {  // sensor 1
        rulesNewRule[5]--;
        if (rulesNewRule[5] < 0) {rulesNewRule[5] = 0;}
        document.getElementById('delaySeconds').innerHTML = rulesNewRule[5];
    }
    else {  // sensor 2
        rulesNewRule[12]--;
        if (rulesNewRule[12] < 0) {rulesNewRule[12] = 0;}
        document.getElementById('delaySeconds').innerHTML = rulesNewRule[12];
    }
} 

function ruleSensorValueUp(decimals, sensorNumber) {  // adjust sensor value up
    // console.log('ruleSensorValueUp     = ' + type);
    if (sensorNumber == 0) {  // sensor 1
        if (decimals == 1) {rulesNewRule[2] = round(rulesNewRule[2] + 0.1, 1);}
        else if (decimals == 2) {rulesNewRule[2] = round(rulesNewRule[2] + 0.01, 2);}
        document.getElementById('sensorValue').innerHTML = rulesNewRule[2];
    }
    else {  // sensor 2
        if (decimals == 1) {rulesNewRule[9] = round(rulesNewRule[9] + 0.1, 1);}
        else if (decimals == 2) {rulesNewRule[9] = round(rulesNewRule[9] + 0.01, 2);}
        document.getElementById('sensorValue').innerHTML = rulesNewRule[9];
    }
}

function ruleSensorValueDown(decimals, sensorNumber) {  // adjust sensor value down
    // console.log('ruleSensorValueDown   = ' + type); 
    if (sensorNumber == 0) {  // sensor 1
        if (decimals == 1) {rulesNewRule[2] = round(rulesNewRule[2] - 0.1, 1);}
        else if (decimals == 2) {rulesNewRule[2] = round(rulesNewRule[2] - 0.01, 2);}
        if (rulesNewRule[2] < -40) {rulesNewRule[2] = -40;}
        document.getElementById('sensorValue').innerHTML = rulesNewRule[2];
    }
    else {  // sensor 2
        if (decimals == 1) {rulesNewRule[9] = round(rulesNewRule[9] - 0.1, 1);}
        else if (decimals == 2) {rulesNewRule[9] = round(rulesNewRule[9] - 0.01, 2);}
        if (rulesNewRule[9] < -40) {rulesNewRule[9] = -40;}
        document.getElementById('sensorValue').innerHTML = rulesNewRule[9];
    }
}

function getSensorOptionText(divID) {  // used to get text from sensor type drop down box
    var elt = document.getElementById(divID);

    if (elt.selectedIndex == -1)
        return null;

    return elt.options[elt.selectedIndex].text;
}

function addRuleEquipment() {
    // console.log("addRuleEquipment ------------------------ ");
    
    $('#cleanScreen').empty();  // empty window
    document.getElementById('cleanScreen').innerHTML +=
        '<div class="rulesContainer" id="rulesContainer">\
            <div id="rulesContainerStep0"></div>\
            <div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="customRulesList()">Cancel</button>\
            </div>\
        </div>';

    document.getElementById('rulesContainerStep0').innerHTML +=  // 
        '<div class="rulesTitle">Select all the equipment you would like to control!</div>\
        <div class="ruleOptionBox" id="outletBox">\
            <div class="ruleEquipmentHeader">\
                <div style="margin-bottom:10px;">AC Outlets</div>\
                <span style="font-size:12px; color:#FFFFFF; border:solid 1px #686767; padding:5px;">\
                    <span style="color:#6c6c6c;">Grey</span> = <span style="color:#6c6c6c;">No Action</span> &nbsp; &nbsp; &nbsp; &nbsp;\
                    <span style="color:#00b610;">Green</span> = <span style="color:#00b610;">On</span> &nbsp; &nbsp; &nbsp; &nbsp;\
                    <span style="color:#FF0000;">Red</span> = <span style="color:#FF0000;">Off</span> &nbsp; &nbsp; &nbsp; &nbsp;\
                    <span style="color:#00b610;">Green</span> / <span style="color:#FF0000;">Red</span>\
                    = <span style="color:#00b610;">On</span> / <span style="color:#FF0000;">Off &nbsp; &nbsp; &nbsp; &nbsp;</span>\
                    <span style="color:#FF0000;">Red</span> / <span style="color:#00b610;">Green</span>\
                    = <span style="color:#FF0000;">Off</span> / <span style="color:#00b610;">On</span>\
                </span>\
            </div>\
        </div>\
        <div class="ruleOptionBox" id="dcBox">\
            <div class="ruleEquipmentHeader">\
                <div style="margin-bottom:10px;">DC Ports</div>\
                <span style="font-size:12px; color:#FFFFFF; border:solid 1px #686767; padding:5px;">\
                    <span style="color:#6c6c6c;">Grey</span> = <span style="color:#6c6c6c;">No Action</span> &nbsp; &nbsp; &nbsp; &nbsp;\
                    <span style="color:#00b610;">Green</span> = <span style="color:#00b610;">On</span> &nbsp; &nbsp; &nbsp; &nbsp;\
                    <span style="color:#FF0000;">Red</span> = <span style="color:#FF0000;">Off</span> &nbsp; &nbsp; &nbsp; &nbsp;\
                    <span style="color:#00b610;">Green</span> / <span style="color:#FF0000;">Red</span>\
                    = <span style="color:#00b610;">On</span> / <span style="color:#FF0000;">Off &nbsp; &nbsp; &nbsp; &nbsp;</span>\
                    <span style="color:#FF0000;">Red</span> / <span style="color:#00b610;">Green</span>\
                    = <span style="color:#FF0000;">Off</span> / <span style="color:#00b610;">On</span>\
                </span>\
            </div>\
        </div>\
        <div class="ruleOptionBox" id="doseBox">\
            <div class="ruleEquipmentHeader">\
                <div style="margin-bottom:10px;">Dosing Pumps</div>\
                <span style="font-size:12px; color:#FFFFFF; border:solid 1px #686767; padding:5px;">\
                    <span style="color:#6c6c6c;">Grey</span> = <span style="color:#6c6c6c;">No Action</span> &nbsp; &nbsp; &nbsp; &nbsp;\
                    <span style="color:#00b610;">Green</span> = <span style="color:#00b610;">Run</span>\
                </span>\
            </div>\
        </div>';

    rulesNewRuleACPin = [];
    rulesNewRuleAC = [];
    rulesNewRuleACDelay = [];
    rulesNewRuleDCPin = [];
    rulesNewRuleDC = [];
    rulesNewRuleDCDelay = [];
    rulesNewRuleDosePin = [];
    rulesNewRuleDose = [];
    rulesNewRuleDoseDelay = [];
    rulesNewRuleDoseSuspend = [];
    rulesNewRuleDoseML = [];

    for (var i = 0; i < outletPinID.length; i++) {
        if (outletAssigned[i] == 1) {
            rulesNewRuleACPin[i] = outletPinID[i];
            rulesNewRuleAC[i] = 255;
            rulesNewRuleACDelay[i] = 0;
            // create divs for each outlet
            document.getElementById('outletBox').innerHTML += 
                `<div class="outletColumn" id='schOutletPic_` + i + `'></div>`;
                
            // print icon to screen
            document.getElementById('schOutletPic_' + i).innerHTML = 
                `<img onclick="addRuleEquipmentAC(` + i + `)" class='ruleEquipmentImage' id='outlet_` + i + `' src='images/Outlets/OutLD` + outletIconID[i] + `M.png'>\
                </br>` + outletName[i];
        }
    }
    for (var i = 0; i < dcPinID.length; i++) {
        if (dcAssigned[i] == 1) {
            rulesNewRuleDCPin[i] = dcPinID[i];
            rulesNewRuleDC[i] = 255;
            rulesNewRuleDCDelay[i] = 0;
            // create divs for each DC port
            document.getElementById('dcBox').innerHTML += 
                `<div class="outletColumn" id='schDcPic_` + i + `'></div>`;

            // print icon to screen
            document.getElementById('schDcPic_' + i).innerHTML = 
                `<img onclick="addRuleEquipmentDC(`+ i + `)" class='ruleEquipmentImage' id='dc_` + i + `' src='images/Outlets/OutLD` + dcIconID[i] + `M.png'>\
                </br>` + dcName[i];
        }
    }
    for (var i = 0; i < dosePinID.length; i++) {
        rulesNewRuleDosePin[i] = dosePinID[i];
        rulesNewRuleDose[i] = 255;
        rulesNewRuleDoseDelay[i] = 0;
        rulesNewRuleDoseSuspend[i] = 0;
        rulesNewRuleDoseML[i] = 0;

        // create divs for each DC port
        document.getElementById('doseBox').innerHTML += 
            `<div class="outletColumn" id='schDosePic_` + i + `'></div>`;

        // print icon to screen
        document.getElementById('schDosePic_' + i).innerHTML = 
            `<img onclick="addRuleEquipmentDose(` + i + `)" class='ruleEquipmentImage' id='dose_` + i + `' src='images/Outlets/OutLD24M.png'>\
            </br>` + doseName[i];
    }

    document.getElementById('rulesContainerStep0').innerHTML +=  // draw next step button
        '<div class="ruleOptionContainer" id="outletBox">\
            <div class="ruleSensorOptionBox" id="rulesOpenDelay" onclick="addRuleEquipmentDelay()" style="background-color:#00b610;">\
                Next\
            </div>\
        </div>';

}

function addRuleEquipmentAC(arrayID) {  // update equipment icon color
    // console.log("addRuleEquipmentAC ------------------------ ");
    if (rulesNewRuleAC[arrayID] == 255) {  // on
        rulesNewRuleAC[arrayID] = 1;
        document.getElementById('outlet_' + arrayID).style.background = "";
        document.getElementById('outlet_' + arrayID).style.backgroundColor = "#00b610";
    }
    else if (rulesNewRuleAC[arrayID] == 1) {  // off
        rulesNewRuleAC[arrayID] = 2;
        document.getElementById('outlet_' + arrayID).style.background = "";
        document.getElementById('outlet_' + arrayID).style.backgroundColor = "#FF0000";
    }
    else if (rulesNewRuleAC[arrayID] == 2) {  // on/off
        rulesNewRuleAC[arrayID] = 3;
        document.getElementById('outlet_' + arrayID).style.background = "linear-gradient(90deg, #00b610 50%, #FF0000 50%)";
    }
    else if (rulesNewRuleAC[arrayID] == 3) {  // off/on
        rulesNewRuleAC[arrayID] = 4;
        document.getElementById('outlet_' + arrayID).style.background = "linear-gradient(90deg, #FF0000 50%, #00b610 50%)";
    }
    else {  // no action
        rulesNewRuleAC[arrayID] = 255;
        document.getElementById('outlet_' + arrayID).style.background = "";
        document.getElementById('outlet_' + arrayID).style.backgroundColor = "#444444";
    }
}

function addRuleEquipmentDC(arrayID) {
    // console.log("addRuleEquipmentDC ------------------------ ");
    if (rulesNewRuleDC[arrayID] == 255) {
        rulesNewRuleDC[arrayID] = 1;
        document.getElementById('dc_' + arrayID).style.background = "";
        document.getElementById('dc_' + arrayID).style.backgroundColor = "#00b610";
    }
    else if (rulesNewRuleDC[arrayID] == 1) {
        rulesNewRuleDC[arrayID] = 2;
        document.getElementById('dc_' + arrayID).style.background = "";
        document.getElementById('dc_' + arrayID).style.backgroundColor = "#FF0000";
    }
    else if (rulesNewRuleDC[arrayID] == 2) {
        rulesNewRuleDC[arrayID] = 3;
        document.getElementById('dc_' + arrayID).style.background = "linear-gradient(90deg, #00b610 50%, #FF0000 50%)";
    }
    else if (rulesNewRuleDC[arrayID] == 3) {
        rulesNewRuleDC[arrayID] = 4;
        document.getElementById('dc_' + arrayID).style.background = "linear-gradient(90deg, #FF0000 50%, #00b610 50%)";
    }
    else {
        rulesNewRuleDC[arrayID] = 255;
        document.getElementById('dc_' + arrayID).style.background = "";
        document.getElementById('dc_' + arrayID).style.backgroundColor = "#444444";
    }
}

function addRuleEquipmentDose(arrayID) {
    // console.log("addRuleEquipmentDose ------------------------ ");
    if (rulesNewRuleDose[arrayID] == 255) {
        rulesNewRuleDose[arrayID] = 1;
        document.getElementById('dose_' + arrayID).style.background = "";
        document.getElementById('dose_' + arrayID).style.backgroundColor = "#00b610";
    }
    else {
        rulesNewRuleDose[arrayID] = 255;
        document.getElementById('dose_' + arrayID).style.background = "";
        document.getElementById('dose_' + arrayID).style.backgroundColor = "#444444";
    }
}

function addRuleEquipmentDelay() {
    // console.log("addRuleEquipmentDelay ------------------------ ");

    // console.log("rulesNewRuleACPin.length  = " + rulesNewRuleACPin.length);
    // console.log("rulesNewRuleAC.length     = " + rulesNewRuleAC.length);
    // console.log("rulesNewRuleACPin   = " + rulesNewRuleACPin);
    // console.log("rulesNewRuleAC      = " + rulesNewRuleAC);
    // console.log("rulesNewRuleDCPin.length  = " + rulesNewRuleDCPin.length);
    // console.log("rulesNewRuleDC.length     = " + rulesNewRuleDC.length);
    // console.log("rulesNewRuleDCPin   = " + rulesNewRuleDCPin);
    // console.log("rulesNewRuleDC      = " + rulesNewRuleDC);
    // console.log("rulesNewRuleDosePin = " + rulesNewRuleDosePin);
    // console.log("rulesNewRuleDose    = " + rulesNewRuleDose);

    $('#cleanScreen').empty();  // empty window
    document.getElementById('cleanScreen').innerHTML +=
        '<div class="rulesContainer" id="rulesContainer">\
            <div id="rulesContainerStep0"></div>\
            <div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="customRulesList()">Cancel</button>\
            </div>\
        </div>';

    document.getElementById('rulesContainerStep0').innerHTML +=  // 
        '<div class="rulesTitle">You can add a delay before the equipment is switched!</div>';

    var headerLoaded = 0;  // track if header was loaded
    var onOffExtra = 0;  // track if a duplicate outlet is needed due to on/off feature
    var duplicates = 0;  // track how many on/off or off/on rules exist so we can shift arrays to get name and icon of equipment
    for (var i = 0; i < rulesNewRuleAC.length; i++) {  // go through all possible outlets
        if (rulesNewRuleAC[i] != 255) {  // only load AC outlets that were selected
            if (headerLoaded == 0) {  // load header for AC outlets
                document.getElementById('rulesContainerStep0').innerHTML +=  // 
                    '<div class="ruleOptionContainer" id="outletBox"><div class="ruleEquipmentHeader">AC Outlets</div></div>';
                headerLoaded = 1;  // mark header loaded
            }
            var text = "";  // text to display based on selection            
            if (rulesNewRuleAC[i] == 1) {text = "on";}  // turn on
            else if (rulesNewRuleAC[i] == 2) {text = "off";}  // turn off
            else if (rulesNewRuleAC[i] == 3) {  // turn on and off
                if (onOffExtra == 0) {text = "on";}  // turn on
                else if (onOffExtra == 1) {text = "off";}  // turn off
            }
            else if (rulesNewRuleAC[i] == 4) {  // turn off and on
                if (onOffExtra == 0) {text = "off";}  // turn off
                else if (onOffExtra == 1) {text = "on";}  // turn on
            }

            // create divs for each outlet
            document.getElementById('outletBox').innerHTML += 
                `<div class="ruleEquipmentDelayContainer">\
                    <div class="ruleEquipmentDelayIcon" id='schOutletPic_` + i + `'></div>\
                    <div class="ruleEquipmentDelayBox">\
                        <div class="ruleEquipmentIgnore">Delay Switching ` + text + ` for </div>\
                        <input class="ruleEquipmentDelay" type="text" id='ruleEquipmentACDelay_` + i + `' onchange="addRuleUpdateEquipDelay(0,` + i + `)" onfocusout="addRuleUpdateEquipDelay(0,` + i + `)" value="` + rulesNewRuleACDelay[i] + `" autocomplete="off">\
                        <div class="ruleEquipmentDelay" style="padding-left:5px;">Seconds</div>\
                    </div>\
                </div>`;
                
            // print icon to screen
            document.getElementById('schOutletPic_' + i).innerHTML = 
                `<img class='ruleEquipmentImage' id='outlet_` + i + `' src='images/Outlets/OutLD` + outletIconID[i - duplicates] + `M.png'>\
                </br>` + outletName[i - duplicates];
            
            if (rulesNewRuleAC[i] == 1) {document.getElementById('outlet_' + i).style.backgroundColor = "#00b610";}  // make icon green for on
            else if (rulesNewRuleAC[i] == 2) {document.getElementById('outlet_' + i).style.backgroundColor = "#FF0000";}  // make icon red for off
            else if (rulesNewRuleAC[i] == 3) {  // outlet is on and off
                if (onOffExtra == 0) {  // update first outlet
                    document.getElementById('outlet_' + i).style.backgroundColor = "#00b610";  // make icon green for on
                    rulesNewRuleACDelay[rulesNewRuleAC.length] = 0;  // add new element to array for delay, this is the duplicate for off
                    // rulesNewRuleAC[rulesNewRuleAC.length] = 255;  // add new element to array for outlet, this is the duplicate for off
                    
                    for (var g = rulesNewRuleAC.length; g > i; g--) {  // go through array from end to current location in array
                        rulesNewRuleACPin[g] = rulesNewRuleACPin[g-1];  // shift outletPinID in existing array so duplicate can be squeezed in
                        rulesNewRuleAC[g] = rulesNewRuleAC[g-1];  // shift outletPinID in existing array so duplicate can be squeezed in
                    }
                    rulesNewRuleAC[i+1] = 3;  // update duplicate with switchID
                    onOffExtra++;  // get ready for the duplicate
                    duplicates++;  // count as an on/off rule
                }
                else {document.getElementById('outlet_' + i).style.backgroundColor = "#FF0000"; onOffExtra = 0;}  // update duplicate icon - make icon red for off
            }
            else if (rulesNewRuleAC[i] == 4) {  // outlet is off and on
                if (onOffExtra == 0) {  // update first outlet
                    document.getElementById('outlet_' + i).style.backgroundColor = "#FF0000";  // make icon green for on
                    rulesNewRuleACDelay[rulesNewRuleAC.length] = 0;  // add new element to array for delay, this is the duplicate for off
                    // rulesNewRuleAC[rulesNewRuleAC.length] = 255;  // add new element to array for outlet, this is the duplicate for off
                    
                    for (var g = rulesNewRuleAC.length; g > i; g--) {  // go through array from end to current location in array
                        rulesNewRuleACPin[g] = rulesNewRuleACPin[g-1];  // shift outletPinID in existing array so duplicate can be squeezed in
                        rulesNewRuleAC[g] = rulesNewRuleAC[g-1];  // shift outletPinID in existing array so duplicate can be squeezed in
                    }
                    rulesNewRuleAC[i+1] = 4;  // update duplicate with switchID
                    onOffExtra++;  // get ready for the duplicate
                    duplicates++;  // count as an off/on rule
                }
                else {document.getElementById('outlet_' + i).style.backgroundColor = "#00b610"; onOffExtra = 0;}  // update duplicate icon - make icon red for off 
            }
        }
    }

    headerLoaded = 0;  // track if header was loaded
    onOffExtra = 0;  // track if a duplicate DC port is needed due to on/off feature
    duplicates = 0;  // track how many on/off or off/on rules exist so we can shift arrays to get name and icon of equipment
    for (var i = 0; i < rulesNewRuleDC.length; i++) {  // go through all possible dc ports
        if (rulesNewRuleDC[i] != 255) {  // only load DC ports that were selected
            if (headerLoaded == 0) {  // load header for DC ports
                document.getElementById('rulesContainerStep0').innerHTML +=  // 
                    '<div class="ruleOptionContainer" id="dcBox"><div class="ruleEquipmentHeader">DC Ports</div></div>';
                headerLoaded = 1;  // mark header loaded
            }

            var text = "";  // text to display based on selection   
            if (rulesNewRuleDC[i] == 1) {text = "on"}  // turn on
            else if (rulesNewRuleDC[i] == 2) {text = "off"}  // turn off
            else if (rulesNewRuleDC[i] == 3) {  // turn on and off
                if (onOffExtra == 0) {text = "on"}  // turn on
                else if (onOffExtra == 1) {text = "off"}  // turn off
            }
            else if (rulesNewRuleDC[i] == 4) {  // turn off and on
                if (onOffExtra == 0) {text = "off"}  // turn off
                else if (onOffExtra == 1) {text = "on"}  // turn on
            }

            // create divs for each DC port
            document.getElementById('dcBox').innerHTML += 
                `<div class="ruleEquipmentDelayContainer">\
                    <div class="ruleEquipmentDelayIcon" id='schDcPic_` + i + `'></div>\
                    <div class="ruleEquipmentDelayBox">\
                        <div class="ruleEquipmentIgnore">Delay Switching ` + text + ` for </div>\
                        <input class="ruleEquipmentDelay" type="text" id='ruleEquipmentDCDelay_` + i + `' onchange="addRuleUpdateEquipDelay(1,` + i + `)" onfocusout="addRuleUpdateEquipDelay(1,` + i + `)" value="` + rulesNewRuleDCDelay[i] + `" autocomplete="off">\
                        <div class="ruleEquipmentDelay" style="padding-left:5px;">Seconds</div>\
                    </div>\
                </div>`;
                
            // print icon to screen
            document.getElementById('schDcPic_' + i).innerHTML = 
                `<img class='ruleEquipmentImage' id='dc_` + i + `' src='images/Outlets/OutLD` + dcIconID[i - duplicates] + `M.png'>\
                </br>` + dcName[i - duplicates];
            
            if (rulesNewRuleDC[i] == 1) {document.getElementById('dc_' + i).style.backgroundColor = "#00b610";}  // make icon green for on
            else if (rulesNewRuleDC[i] == 2) {document.getElementById('dc_' + i).style.backgroundColor = "#FF0000";}  // make icon red for off
            else if (rulesNewRuleDC[i] == 3) {  // DC is on and off
                if (onOffExtra == 0) {  // update first DC port
                    document.getElementById('dc_' + i).style.backgroundColor = "#00b610";  // make icon green for on
                    rulesNewRuleDCDelay[rulesNewRuleDC.length] = 0;  // add new element to array for delay, this is the duplicate for off
                    // rulesNewRuleDC[rulesNewRuleDC.length] = 255;  // add new element to array for outlet, this is the duplicate for off
                    
                    for (var g = rulesNewRuleDC.length; g > i; g--) {  // go through array from end to current location in array
                        rulesNewRuleDCPin[g] = rulesNewRuleDCPin[g-1];  // shift outletPinID in existing array so duplicate can be squeezed in
                        rulesNewRuleDC[g] = rulesNewRuleDC[g-1];  // shift outletPinID in existing array so duplicate can be squeezed in
                    }
                    rulesNewRuleDC[i+1] = 3;  // update duplicate with switchID
                    onOffExtra++;  // get ready for the duplicate
                    duplicates++;
                }
                else {document.getElementById('dc_' + i).style.backgroundColor = "#FF0000"; onOffExtra = 0;}  // update duplicate icon - make icon red for off
            }
            else if (rulesNewRuleDC[i] == 4) {  // outlet is off and on
                if (onOffExtra == 0) {  // update first DC port
                    document.getElementById('dc_' + i).style.backgroundColor = "#FF0000";  // make icon green for on
                    rulesNewRuleDCDelay[rulesNewRuleDC.length] = 0;  // add new element to array for delay, this is the duplicate for off
                    // rulesNewRuleDC[rulesNewRuleDC.length] = 255;  // add new element to array for outlet, this is the duplicate for off
                    
                    for (var g = rulesNewRuleDC.length; g > i; g--) {  // go through array from end to current location in array
                        rulesNewRuleDCPin[g] = rulesNewRuleDCPin[g-1];  // shift outletPinID in existing array so duplicate can be squeezed in
                        rulesNewRuleDC[g] = rulesNewRuleDC[g-1];  // shift outletPinID in existing array so duplicate can be squeezed in
                    }
                    rulesNewRuleDC[i+1] = 4;  // update duplicate with switchID
                    onOffExtra++;  // get ready for the duplicate
                    duplicates++;
                }
                else {document.getElementById('dc_' + i).style.backgroundColor = "#00b610"; onOffExtra = 0;}  // update duplicate icon - make icon red for off
            }
        }
    }

    headerLoaded = 0;  // track if header was loaded
    for (var i = 0; i < rulesNewRuleDose.length; i++) {  // go through all possible dosing pumps
        if (rulesNewRuleDose[i] != 255) {  // only load dosing pumps that were selected
            if (headerLoaded == 0) {  // load header for DC ports
                document.getElementById('rulesContainerStep0').innerHTML +=  // 
                    '<div class="ruleOptionContainer" id="doseBox"><div class="ruleEquipmentHeader">Dosing Pumps</div></div>';
                headerLoaded = 1;  // mark header loaded
            }

            // create divs for each dosing pump
            document.getElementById('doseBox').innerHTML += 
                `<div class="ruleEquipmentDelayContainer">\
                    <div class="ruleEquipmentDelayIcon" id='schDosePic_` + i + `'></div>\
                    <div class="ruleEquipmentDelayBox">\
                        <div class="ruleEquipmentOptionBox">\
                            <div class="ruleEquipmentIgnore">Dose </div>\
                            <div class="ruleEquipmentDelayInline">
                                <input class="ruleEquipmentDelay" type="number" id='ruleEquipmentDoseML_` + i + `' onchange="addRuleUpdateDoseML(` + i + `)" onfocusout="addRuleUpdateDoseML(` + i + `)" value="` + rulesNewRuleDoseML[i] + `" autocomplete="off">\
                                <div class="ruleEquipmentDelay" style="padding-left:5px;">mL's</div>\
                            </div>\
                            <div class="ruleEquipmentIgnore">Delay Dosing For </div>\
                            <div class="ruleEquipmentDelayInline">
                                <input class="ruleEquipmentDelay" type="number" id='ruleEquipmentDoseDelay_` + i + `' onchange="addRuleUpdateEquipDelay(2,` + i + `)" onfocusout="addRuleUpdateEquipDelay(2,` + i + `)" value="` + rulesNewRuleDoseDelay[i] + `" autocomplete="off">\
                                <div class="ruleEquipmentDelay" style="padding-left:5px;">Seconds</div>\
                            </div>\
                        </div>\
                        <div class="ruleEquipmentOptionBox">\
                            <div class="ruleEquipmentIgnore">Suspend dosing for </div>\
                            <div class="ruleEquipmentDelayInline">
                                <input class="ruleEquipmentDelay" type="number" id='ruleEquipmentDoseSuspend_` + i + `' onchange="addRuleUpdateDoseSuspend(` + i + `)" onfocusout="addRuleUpdateDoseSuspend(` + i + `)" value="` + rulesNewRuleDoseSuspend[i] + `" autocomplete="off">\
                                <div class="ruleEquipmentDelay" style="padding-left:5px;">Minutes</div>\
                            </div>\
                        </div>\
                    </div>\
                </div>`;
                
            // print icon to screen
            document.getElementById('schDosePic_' + i).innerHTML = 
                `<img class='ruleEquipmentImage' id='dose_` + i + `' src='images/Outlets/OutLD24M.png'>\
                </br>` + doseName[i];
            
            if (rulesNewRuleDose[i] == 1) {document.getElementById('dose_' + i).style.backgroundColor = "#00b610";}  // make icon green for on
            else if (rulesNewRuleDose[i] == 2) {document.getElementById('dose_' + i).style.backgroundColor = "#FF0000";}  // make icon red for off
        }
    }
    document.getElementById('rulesContainerStep0').innerHTML +=  // draw next step button
        '<div class="ruleOptionContainer" id="doseBox">\
            <div class="ruleSensorOptionBox" id="rulesOpenDelay" onclick="addRuleAlerts()" style="background-color:#00b610;">\
                Next\
            </div>\
        </div>';

    if (windowWidth < 395) {$(".ruleEquipmentIgnore").css("textAlign", "left");}
    else {$(".ruleEquipmentIgnore").css("textAlign", "right");}
        
    // console.log("");
    // console.log("rulesNewRuleACPin.length  = " + rulesNewRuleACPin.length);
    // console.log("rulesNewRuleAC.length     = " + rulesNewRuleAC.length);
    // console.log("rulesNewRuleACPin   = " + rulesNewRuleACPin);
    // console.log("rulesNewRuleAC      = " + rulesNewRuleAC);
    // console.log("rulesNewRuleDCPin.length  = " + rulesNewRuleDCPin.length);
    // console.log("rulesNewRuleDC.length     = " + rulesNewRuleDC.length);
    // console.log("rulesNewRuleDCPin   = " + rulesNewRuleDCPin);
    // console.log("rulesNewRuleDC      = " + rulesNewRuleDC);
    // console.log("rulesNewRuleDosePin = " + rulesNewRuleDosePin);
    // console.log("rulesNewRuleDose    = " + rulesNewRuleDose);
    // console.log("");
    // console.log("");
}

function addRuleValidate() {
    // console.log("addRuleValidate ------------------------ ");
    rulesNewRule[18] = document.getElementById("ruleCustomName").value;  // get name from form
    // console.log("rulesNewRule[18] = " + rulesNewRule[18]);
    if ((rulesNewRule[18] == null) || (rulesNewRule[18] == "")) {  // check if password is blank.    
        document.getElementById('fieldError1').style.display = "inline-block";  // show error
        document.getElementById('fieldError1').innerHTML = "You need a name for the custom rule!";
        document.getElementById('ruleCustomName').style.border = "2px solid rgb(255, 0, 0)";
        document.getElementById('ruleCustomName').focus();
        return 0;
    }
    else {
        document.getElementById('fieldError1').style.display = "none";  // show error
        document.getElementById('ruleCustomName').style.border = "";
        return 1;
    }
}

function addRuleAlerts() {
    // console.log("");
    // console.log("addRuleAlerts ------------------------ ");
    
    rulesNewRule[16] = 0;
    rulesNewRule[17] = 0;
    rulesNewRule[18] = "";

    $('#cleanScreen').empty();  // empty window
    document.getElementById('cleanScreen').innerHTML +=
        '<div class="rulesContainer" id="rulesContainer">\
            <div id="rulesContainerStep0"></div>\
            <div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="customRulesList()">Cancel</button>\
            </div>\
        </div>';

    document.getElementById('rulesContainerStep0').innerHTML +=  // 
        '<div class="rulesTitle">Give the new custom rule a name!</div>';
    
    document.getElementById('rulesContainerStep0').innerHTML +=  // 
        '<div class="ruleAlertsContainer">\
            <div class="schDaysContainer">\
                <div class="schFieldName">Custom Name</div>\
                <input class="schField" type="text" id="ruleCustomName" value="' + rulesNewRule[18] + '" onfocusout="addRuleValidate()" autocomplete="off">\
                <div class="fieldError" id="fieldError1"></div>\
            </div>\
        </div>';

    document.getElementById('rulesContainerStep0').innerHTML +=  // 
        '<div class="rulesTitle" style="margin-top:15px;">Select any alerts you would like to use!</div>';
    
    document.getElementById('rulesContainerStep0').innerHTML +=  // 
        '<div class="ruleOptionContainer" id="alertBox2"></div>';

    document.getElementById('alertBox2').innerHTML += 
        `<div class="ruleAlertsContainer" onclick="addRuleUpdateAlert(0)">\
            <div class="ruleEquipmentDelayIcon"><img class='ruleEquipmentImage' id='dashboard' src='images/icons/alerts2.png'></div>\
            <div class="ruleAlertText">Enable or Disable Dashboard Alert</div>\
        </div>\
        <div class="ruleAlertsContainer" onclick="addRuleUpdateAlert(1)">\
            <div class="ruleEquipmentDelayIcon"><img class='ruleEquipmentImage' id='email' src='images/icons/email.png'></div>\
            <div class="ruleAlertText">Enable or Disable Email Alert</div>\
        </div>`;

    document.getElementById('rulesContainerStep0').innerHTML +=  // draw review button
        '<div class="ruleOptionContainer">\
            <div class="ruleSensorOptionBox" id="rulesOpenDelay" onclick="addRuleReview()" style="background-color:#00b610;">\
                Review Custom Rule\
            </div>\
        </div>';

    document.getElementById('dashboard').style.backgroundColor = "#444444";
    document.getElementById('email').style.backgroundColor = "#444444";
}

function addRuleUpdateAlert(type) {
    // console.log("addRuleUpdateAlert ------------------------ ");
    if (type == 0) {  // dashboard alert
        if (rulesNewRule[16] == 0) {
            rulesNewRule[16] = 1;
            document.getElementById('dashboard').style.backgroundColor = "#00b610";
        }
        else {
            rulesNewRule[16] = 0;
            document.getElementById('dashboard').style.backgroundColor = "#444444";
        }
    }
    if (type == 1) {  // email alert
        if (rulesNewRule[17] == 0) {
            rulesNewRule[17] = 1;
            document.getElementById('email').style.backgroundColor = "#00b610";
        }
        else {
            rulesNewRule[17] = 0;
            document.getElementById('email').style.backgroundColor = "#444444";
        }
    }
}

function addRuleReview() {
    // console.log("");
    console.log("addRuleReview ------------------------ ");
    var pass = addRuleValidate();
    if (pass == 0) {return;}
    
    displayScreen = 12;
    rulesNewRule[18] = document.getElementById('ruleCustomName').value;
    
    for (var c=0; c < rulesNewRule.length; c++) {  // 
        // console.log("rulesNewRule[" + c + "] = " + rulesNewRule[c]);
    }

    // console.log("rulesNewRuleACPin.length  = " + rulesNewRuleACPin.length);
    // console.log("rulesNewRuleAC.length     = " + rulesNewRuleAC.length);
    // console.log("rulesNewRuleACPin      = " + rulesNewRuleACPin);
    // console.log("rulesNewRuleAC         = " + rulesNewRuleAC);
    // console.log("rulesNewRuleACDelay    = " + rulesNewRuleACDelay);
    // console.log("rulesNewRuleDCPin      = " + rulesNewRuleDCPin);
    // console.log("rulesNewRuleDC         = " + rulesNewRuleDC);
    // console.log("rulesNewRuleDCDelay    = " + rulesNewRuleDCDelay);
    // console.log("rulesNewRuleDosePin    = " + rulesNewRuleDosePin);
    // console.log("rulesNewRuleDose       = " + rulesNewRuleDose);
    // console.log("rulesNewRuleDoseDelay  = " + rulesNewRuleDoseDelay);
    // console.log("rulesNewRuleDoseSuspend = " + rulesNewRuleDoseSuspend);
    // console.log("rulesNewRuleDoseML     = " + rulesNewRuleDoseML);

    
    document.getElementById('cleanScreen').innerHTML =
        "<div class='rulesContainer' id='rulesContainer'>\
        <div class='settingsTitle ruleList' id='ruleList_'>" + rulesNewRule[18] + "</div>\
            <div class='rulesListCol1' id='rulesListCol1_'>\
                <div class='rulesListCol1_Sensors' id='rulesListCol1_Sensors_'>\
                    <div class='ruleListSensorLineBox' id='ruleListSensorLineBox_'></div>\
                </div>\
                <div class='rulesListCol1_Equipment' id='rulesListCol1_Equipment_'></div>\
                <div class='ruleListAlertsBox' id='ruleListAlertsBox_'></div>\
            </div>\
        </div>";

    var totalSensors = 0;
    if (rulesNewRule[1] == 0) {totalSensors = 1;}
    else {totalSensors = 2;}

    for (var c=0; c < totalSensors; c++) {  // go through all sensors for new rule
        var padding = 0;
        if (c == 0) {padding = 0;}
        else {padding = 7;}
        // console.log("c = " + c);
        var ruleText = "";
        var ruleLogicText = "";
        var ruleNameText = "";
        if ((rulesNewRule[6+padding] == 3) && (rulesNewRule[4+padding] == 1)) {  // ph
            ruleText = "is greater than " + round(rulesNewRule[2+padding],3);
        }
        else if ((rulesNewRule[6+padding] == 3) && (rulesNewRule[4+padding] == 0)) {  // ph
            ruleText = "is less than " + round(rulesNewRule[2+padding],3);
        }
        else if ((rulesNewRule[6+padding] == 4) && (rulesNewRule[4+padding] == 1)) {  // DHT22
            ruleText = "is greater than " + round(rulesNewRule[2+padding],1);
            if (rulesNewRule[3+padding] == 0) {ruleText += "\u00B0";}  // temperature
            else if (rulesNewRule[3+padding] == 1) {ruleText += "%";}  // humidity
        }
        else if ((rulesNewRule[6+padding] == 4) && (rulesNewRule[4+padding] == 0)) {  // DHT22
            ruleText = "is less than " + round(rulesNewRule[2+padding],1);
            if (rulesNewRule[3+padding] == 0) {ruleText += "\u00B0";}  // temperature
            else if (rulesNewRule[3+padding] == 1) {ruleText += "%";}  // humidity
        }
        else if ((rulesNewRule[6+padding] == 5) && (rulesNewRule[4+padding] == 1)) {  // temperature
            ruleText = "is greater than " + round(rulesNewRule[2+padding],1) + "\u00B0";
        }
        else if ((rulesNewRule[6+padding] == 5) && (rulesNewRule[4+padding] == 0)) {  // temperature
            ruleText = "is less than " + round(rulesNewRule[2+padding],1) + "\u00B0";
        }
        else if (rulesNewRule[6+padding] == 6) {  // non contact sensor
            if (rulesNewRule[2+padding] == 1) {
                ruleText = "is sensing water";
            }
            else if (rulesNewRule[2+padding] == 0) {
                ruleText = "is not sensing water";
            }
        }
        else if (rulesNewRule[6+padding] == 14) {  // toggle switch
            if (rulesNewRule[2+padding] == 1) {
                ruleText = "is on";
            }
            else if (rulesNewRule[2+padding] == 0) {
                ruleText = "is off";
            }
        }
        else if (rulesNewRule[2+padding] == 1) {  // water sensor
            ruleText = "is touching water";
        }
        else if (rulesNewRule[2+padding] == 0) {  // water sensor
            ruleText = "is not touching water";
        }

        if (rulesNewRule[5+padding] > 0) {
            ruleText += " for " + rulesNewRule[5+padding];
            if (rulesNewRule[5+padding] == 1) {ruleText += " consecutive second";}
            else {ruleText += " consecutive seconds";}
        }

        if ((rulesNewRule[6+padding] == 4) && (rulesNewRule[3+padding] == 0)) {
            ruleNameText = " Temperature"
        }
        else if ((rulesNewRule[6+padding] == 4) && (rulesNewRule[3+padding] == 1)) {
            ruleNameText = " Humidity"
        }

        if (c > 0) {
            if (rulesNewRule[1] == 1) {
                ruleLogicText = "AND "
            }
            else if (rulesNewRule[1] == 2) {
                ruleLogicText = " OR "
            }
        }
        
        // print text version of settings for sensor
        document.getElementById('ruleListSensorLineBox_').innerHTML +=
            "<div class='ruleListSensorLine'><span style='color:#FF0000'>" + ruleLogicText + "</span> If " + rulesNewRule[8+padding] + ruleNameText + " " + ruleText + "</div>";
    
    }

    if (rulesNewRule[17] == 1) {  // add email enabled icon
        document.getElementById('ruleListAlertsBox_').innerHTML +=
            '<div class="ruleListAlerts"><i class="bi bi-envelope-fill">&nbsp; Email Enabled</i></div>';
    }

    if (rulesNewRule[16] == 1) {  // add dashboard alert enabled icon
        document.getElementById('ruleListAlertsBox_').innerHTML +=
            '<div class="ruleListAlerts"><i class="bi bi-exclamation-triangle-fill">&nbsp; Dashboard Alert</i></div>';
    }

    // var rulesNewRuleACPin = [];
    // var rulesNewRuleAC = [];
    // var rulesNewRuleACDelay = [];
    // var rulesNewRuleDCPin = [];
    // var rulesNewRuleDC = [];
    // var rulesNewRuleDCDelay = [];
    // var rulesNewRuleDosePin = [];
    // var rulesNewRuleDose = [];
    // var rulesNewRuleDoseDelay = [];
    // var rulesNewRuleDoseML = [];

                    

    var onOffExtra = 0;
    var duplicates = 0;  // track how many on/off or off/on rules exist so we can shift arrays to get name and icon of equipment
    for (var c=0; c < rulesNewRuleAC.length; c++) {  // go through all equipment and print icons
        if (rulesNewRuleAC[c] != 255) {
            // document.getElementById('rulesListCol1_Equipment_').innerHTML += 
            //     '<div class="ruleListIconBox">\
            //         <div class="ruleListSwitchDelay" id="">' + outletName[c-duplicates] + '</div>\
            //         <img id="outletIcon_' + c + '" class="outletDashboard" src="images/Outlets/OutLD' + outletIconID[c-duplicates] + 'S.png" title="' + outletName[c-duplicates] + '">\
            //         <div class="ruleListSwitchDelay" id="acDelay_' + c + '"></div>\
            //     </div>';

            document.getElementById('rulesListCol1_Equipment_').innerHTML += 
                '<div class="ruleListEquipBox">\
                    <div class="ruleListSwitchDelay" id="">' + outletName[c-duplicates] + '</div>\
                    <img id="outletIcon_' + c + '" class="ruleListEquipIcon" src="images/Outlets/OutLD' + outletIconID[c-duplicates] + 'S.png" title="' + outletName[c-duplicates] + '">\
                    <div class="ruleListSwitchDelay" id="acDelay_' + c + '"></div>\
                </div>';

            var ruleText = "";
            if (rulesNewRuleACDelay[c] == 0) {ruleText = "Switches immediately";}
            else if (rulesNewRuleACDelay[c] > 0) {ruleText = "Switches " + rulesNewRuleACDelay[c] + " seconds after rule starts";}                

            document.getElementById('acDelay_' + c).innerHTML += ruleText;

            
            // var ruleText = "";
            // if (rulesNewRuleACDelay[c] == 0) {ruleText = "Immediate";}
            // else if (rulesNewRuleACDelay[c] > 0) {ruleText = rulesNewRuleACDelay[c] + " Second Delay";}

            // document.getElementById('acDelay_' + c).innerHTML += ruleText;

            if (rulesNewRuleAC[c] == 1) {document.getElementById('outletIcon_' + c).style.backgroundColor = "#00b610";}  // make icon green for on
            else if (rulesNewRuleAC[c] == 2) {document.getElementById('outletIcon_' + c).style.backgroundColor = "#FF0000";}  // make icon red for off
            else if (rulesNewRuleAC[c] == 3) {  // outlet is on and off
                if (onOffExtra == 0) {document.getElementById('outletIcon_' + c).style.backgroundColor = "#00b610"; onOffExtra++; duplicates++;}  //update first outlet - make icon green for on
                else if (onOffExtra == 1) {document.getElementById('outletIcon_' + c).style.backgroundColor = "#FF0000"; onOffExtra = 0;}  //update 2nd outlet - make icon red for off
            }
            else if (rulesNewRuleAC[c] == 4) {  // outlet is off and on
                if (onOffExtra == 0) {document.getElementById('outletIcon_' + c).style.backgroundColor = "#FF0000"; onOffExtra++; duplicates++;}  //update first outlet - make icon green for on
                else if (onOffExtra == 1) {document.getElementById('outletIcon_' + c).style.backgroundColor = "#00b610"; onOffExtra = 0;}  //update 2nd outlet - make icon red for off
            }
        }
    }

    onOffExtra = 0;
    duplicates = 0;  // track how many on/off or off/on rules exist so we can shift arrays to get name and icon of equipment
    for (var c=0; c < rulesNewRuleDC.length; c++) {  // go through all equipment and print icons
        if (rulesNewRuleDC[c] != 255) {
            // document.getElementById('rulesListCol1_Equipment_').innerHTML += 
            //     '<div class="ruleListIconBox">\
            //         <div class="ruleListSwitchDelay" id="">' + dcName[c-duplicates] + '</div>\
            //         <img id="dcIcon_' + c + '" class="outletDashboard" src="images/Outlets/OutLD' + dcIconID[c-duplicates] + 'S.png" title="' + dcName[c-onOffExtra] + '">\
            //         <div class="ruleListSwitchDelay" id="dcDelay_' + c + '"></div>\
            //     </div>';
            document.getElementById('rulesListCol1_Equipment_').innerHTML += 
                '<div class="ruleListEquipBox">\
                    <div class="ruleListSwitchDelay" id="">' + dcName[c-duplicates] + '</div>\
                    <img id="dcIcon_' + c + '" class="ruleListEquipIcon" src="images/Outlets/OutLD' + dcIconID[c-duplicates] + 'S.png" title="' + dcName[c-duplicates] + '">\
                    <div class="ruleListSwitchDelay" id="dcDelay_' + c + '"></div>\
                </div>';
                
            // var ruleText = "";
            // if (rulesNewRuleDCDelay[c] == 0) {ruleText = "Immediate";}
            // else if (rulesNewRuleDCDelay[c] > 0) {ruleText = rulesNewRuleDCDelay[c] + " Second Delay";}

            // document.getElementById('dcDelay_' + c).innerHTML += ruleText;

            var ruleText = "";
            if (rulesNewRuleDCDelay[c] == 0) {ruleText = "Switches immediately";}
            else if (rulesNewRuleDCDelay[c] > 0) {ruleText = "Switches " + rulesNewRuleDCDelay[c] + " seconds after rule starts";}                

            document.getElementById('dcDelay_' + c).innerHTML += ruleText;

            if (rulesNewRuleDC[c] == 1) {document.getElementById('dcIcon_' + c).style.backgroundColor = "#00b610";}  // make icon green for on
            else if (rulesNewRuleDC[c] == 2) {document.getElementById('dcIcon_' + c).style.backgroundColor = "#FF0000";}  // make icon red for off
            else if (rulesNewRuleDC[c] == 3) {  // outlet is on and off
                if (onOffExtra == 0) {document.getElementById('dcIcon_' + c).style.backgroundColor = "#00b610"; onOffExtra++; duplicates++;}  //update first outlet - make icon green for on
                else if (onOffExtra == 1) {document.getElementById('dcIcon_' + c).style.backgroundColor = "#FF0000"; onOffExtra = 0;}  //update 2nd outlet - make icon red for off
            }
            else if (rulesNewRuleDC[c] == 4) {  // outlet is off and on
                if (onOffExtra == 0) {document.getElementById('dcIcon_' + c).style.backgroundColor = "#FF0000"; onOffExtra++; duplicates++;}  //update first outlet - make icon green for on
                else if (onOffExtra == 1) {document.getElementById('dcIcon_' + c).style.backgroundColor = "#00b610"; onOffExtra = 0;}  //update 2nd outlet - make icon red for off
            }
        }
    }

    for (var c=0; c < rulesNewRuleDose.length; c++) {  // go through all equipment and print icons
        if (rulesNewRuleDose[c] != 255) {
            // document.getElementById('rulesListCol1_Equipment_').innerHTML += 
            //     '<div class="ruleListIconBox">\
            //         <div class="ruleListSwitchDelay" id="">' + doseName[c] + '</div>\
            //         <img id="doseIcon_' + c + '" class="outletDashboard" src="images/Outlets/OutLD24S.png" title="' + doseName[c] + '">\
            //         <div class="ruleListSwitchDelay" id="doseDelay_' + c + '"></div>\
            //     </div>';
            document.getElementById('rulesListCol1_Equipment_').innerHTML += 
                '<div class="ruleListEquipBox">\
                    <div class="ruleListSwitchDelay" id="">Dosing ' + rulesNewRuleDoseML[c] + ' mL\'s - ' + doseName[c] + '</div>\
                    <img id="doseIcon_' + c + '" class="ruleListEquipIcon" src="images/Outlets/OutLD24S.png" title="' + doseName[c] + '">\
                    <div class="ruleListSwitchDelay" id="doseDelay_' + c + '"></div>\
                    <div class="ruleListSwitchDelay" id="doseSuspendDelay_' + c + '"></div>\
                </div>';

            var ruleText = "";
            if (rulesNewRuleDoseDelay[c] == 0) {ruleText = "Dose immediately";}
            else if (rulesNewRuleDoseDelay[c] > 0) {ruleText = "Dose " + rulesNewRuleDoseDelay[c] + " seconds after rule starts";}                
        
            document.getElementById('doseDelay_' + c).innerHTML += ruleText;
        
            
            ruleText = "";
            if (rulesNewRuleDoseSuspend[c] == 0) {  // no dose delay set in rule so grab default value
                for (var g = 0; g < dosePinID.length; g++){
                    if (rulesNewRuleDosePin[c] == dosePinID[g]) {
                        ruleText = "Suspend dosing for " + rulesNewRuleDoseSuspend[g] + " minutes";
                        break;
                    }
                }
            }
            else if (rulesNewRuleDoseSuspend[c] > 0) {ruleText = "Suspend dosing for " + rulesNewRuleDoseSuspend[c] + " minutes";}
            document.getElementById('doseSuspendDelay_' + c).innerHTML += ruleText;

            // var ruleText = "";
            // if (rulesNewRuleDoseDelay[c] == 0) {ruleText = "Immediate";}
            // else if (rulesNewRuleDoseDelay[c] > 0) {ruleText = rulesNewRuleDoseDelay[c] + " Second Delay";}

            // document.getElementById('doseDelay_' + c).innerHTML += ruleText;

            if (rulesNewRuleDose[c] == 1) {document.getElementById('doseIcon_' + c).style.backgroundColor = "#00b610";}  // make icon green for on
        }
    }

    document.getElementById('cleanScreen').innerHTML +=  // draw save button
        '<div class="ruleOptionContainer">\
            <div class="ruleSensorOptionBox" id="rulesOpenDelay" onclick="addRuleSave()" style="background-color:#00b610;">\
                Save New Rule\
            </div>\
        </div>';

    document.getElementById('cleanScreen').innerHTML +=
        "<div class='widgetButtonBox'>\
            <button class='button _48 home_48' style='margin-top:40px;' type='button' onclick='loadLayout()'></button>\
        </div>";
        
    document.getElementById('rulesListCol1_').style.display = "block";  // expand custom rule
    document.getElementById('ruleList_').style.backgroundColor = "#FF0000";  // change header color
    document.getElementById('ruleList_').style.marginBottom = "0px";  // move rule details up to header
}

function addRuleUpdateDoseSuspend(arrayID) {
    // console.log("addRuleUpdateDoseSuspend ------------------------ ");
    if (document.getElementById('ruleEquipmentDoseSuspend_' + arrayID).value == "") {  // if suspend dosing field is empty add 0
        rulesNewRuleDoseSuspend[arrayID] = 0;
        document.getElementById('ruleEquipmentDoseSuspend_' + arrayID).value = 0;
    }
    else {
        rulesNewRuleDoseSuspend[arrayID] = document.getElementById('ruleEquipmentDoseSuspend_' + arrayID).value;
    }
}

function addRuleUpdateDoseML(arrayID) {
    // console.log("addRuleUpdateEquipDelay ------------------------ ");
    if (document.getElementById('ruleEquipmentDoseML_' + arrayID).value == "") {  // if delay field is empty add 0
        rulesNewRuleDoseML[arrayID] = 0;
        document.getElementById('ruleEquipmentDoseML_' + arrayID).value = 0;
    }
    else {
        rulesNewRuleDoseML[arrayID] = document.getElementById('ruleEquipmentDoseML_' + arrayID).value;
    }
}

function addRuleUpdateEquipDelay(source, arrayID) {
    // console.log("addRuleUpdateEquipDelay ------------------------ ");
    if (source == 0) {
        if (document.getElementById('ruleEquipmentACDelay_' + arrayID).value == "") {  // if delay field is empty add 0
            rulesNewRuleACDelay[arrayID] = 0;
            document.getElementById('ruleEquipmentACDelay_' + arrayID).value = 0;
        }
        else {
            rulesNewRuleACDelay[arrayID] = document.getElementById('ruleEquipmentACDelay_' + arrayID).value;
        }
    }
    else if (source == 1) {
        if (document.getElementById('ruleEquipmentDCDelay_' + arrayID).value == "") {  // if delay field is empty add 0
            rulesNewRuleDCDelay[arrayID] = 0;
            document.getElementById('ruleEquipmentDCDelay_' + arrayID).value = 0;
        }
        else {
            rulesNewRuleDCDelay[arrayID] = document.getElementById('ruleEquipmentDCDelay_' + arrayID).value;
        }
    }
    else if (source == 2) {
        if (document.getElementById('ruleEquipmentDoseDelay_' + arrayID).value == "") {  // if delay field is empty add 0
            rulesNewRuleDoseDelay[arrayID] = 0;
            document.getElementById('ruleEquipmentDoseDelay_' + arrayID).value = 0;
        }
        else {
            rulesNewRuleDoseDelay[arrayID] = document.getElementById('ruleEquipmentDoseDelay_' + arrayID).value;
        }
    }
    // console.log("rulesNewRuleACDelay[arrayID] = " + rulesNewRuleACDelay[arrayID]);
    // console.log("document.getElementById('ruleEquipmentDelay_' + arrayID).value = " + document.getElementById('ruleEquipmentDelay_' + arrayID).value);

}

function expandCustomRule(arrayID) {  // expand custom rule
    // console.log('expandCustomRule------ ' + arrayID);
    // show or hide custom rule details
    if (document.getElementById('rulesListCol1_' + arrayID).style.display === "block") {  // expand custom rule
        document.getElementById('rulesListCol1_' + arrayID).style.display = "none";  // collapse custom rule
        // document.getElementById('ruleList_' + arrayID).style.backgroundColor = "#00b610";  // change header color
        document.getElementById('ruleList_' + arrayID).style.marginBottom = "10px";  // move rule details up to header
    }
    else {  // expand custom rule
        document.getElementById('rulesListCol1_' + arrayID).style.display = "block";  // expand custom rule
        // document.getElementById('ruleList_' + arrayID).style.backgroundColor = "#FF0000";  // change header color
        document.getElementById('ruleList_' + arrayID).style.marginBottom = "0px";  // move rule details up to header
    }
}

function enableRule(arrayID) {  // enable custom rule
    // console.log('enableRule------ ' + arrayID);
    expandCustomRule(arrayID);

    if (rulesEnabled[arrayID] == 0) {
        rulesEnabled[arrayID] = 1;
        document.getElementById('ruleList_' + arrayID).style.backgroundColor = "rgb(2, 38, 240)";  // change header color
        document.getElementById('ruleList_' + arrayID).style.color = "#FFFFFF";  // change custom rule name color
        document.getElementById('enableRule_' + arrayID).style.color = "#FFFFFF";  // change header color
        document.getElementById('enableRule_' + arrayID).classList.remove('bi-toggle-off');
        document.getElementById('enableRule_' + arrayID).classList.add('bi-toggle-on');
    }
    else {
        rulesEnabled[arrayID] = 0;
        document.getElementById('ruleList_' + arrayID).style.backgroundColor = "#292929";  // change header color
        document.getElementById('ruleList_' + arrayID).style.color = "#6a6a6a";  // change custom rule name color
        document.getElementById('enableRule_' + arrayID).style.color = "#FF0000";  // change header color
        document.getElementById('enableRule_' + arrayID).classList.remove('bi-toggle-on');
        document.getElementById('enableRule_' + arrayID).classList.add('bi-toggle-off');
    }

    var command = "122," + ruleID[arrayID];
    sendToBackend(command);
    // console.log('deleteRule------ ' + command);
}

function editRule(arrayID) {  // edit custom rule
    // console.log('editRule------ ' + arrayID);
    expandCustomRule(arrayID);
    $('#popupBackground').show();  // grey out background
    $('.ds18b20Popup-body').empty();
    ds18b20Popup.style.display = "block";
    document.querySelector("body").style.overflow = 'hidden';
    $('.ds18b20PopupHeader').empty();
    
    $(".ds18b20PopupHeader").append("Edit Custom Rule");
    $(".ds18b20Popup-body").append(
        '<div style="text-align: center;">\
            <p>&nbsp;</p>\
            <p>Sorry this isn\'t available yet, for now delete the custom rule and create a new one.</p>\
            <div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="closeDs18b20Popup()">Close</button>\
            </div></br>\
        </div>');
}

function deleteRuleConfirm(arrayID) {  // delete custom rule
    // console.log('deleteRuleConfirm------ ' + arrayID);
    expandCustomRule(arrayID);

    $('#popupBackground').show();  // grey out background
    $('.ds18b20Popup-body').empty();
    ds18b20Popup.style.display = "block";
    document.querySelector("body").style.overflow = 'hidden';
    $('.ds18b20PopupHeader').empty();
    
    $(".ds18b20PopupHeader").append("Delete Custom Rule");
    $(".ds18b20Popup-body").append(
        '<div style="text-align: center;">\
            <p>&nbsp;</p>\
            <p>Are you sure you want to delete the custom rule "' + rulesName[arrayID] + '"?</p>\
            <div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="deleteRule(`' + arrayID + '`)">Yes</button>\
                <button class="button _wide" type="button" onclick="closeDs18b20Popup()">No</button>\
            </div></br>\
        </div>');
}

function deleteRule(arrayID) {  // delete custom rule
    // console.log('deleteRule------ ' + arrayID);
    closeDs18b20Popup();

    displayScreen = 12;
    var command = "121," + ruleID[arrayID];
    sendToBackend(command);
    // console.log('deleteRule------ ' + command);
}

function addRuleSave() {  // print temporary array to track sensor options
    console.log("");
    console.log("addRuleSave ------------------------ ");
    // 0  = Rule Type
    // 1  = Logic for second sensor
    // 2  = Sensor 1 value
    // 3  = Sensor 1 sensor data type
    // 4  = Sensor 1 less than or greater than
    // 5  = Sensor 1 stability delay
    // 6  = Sensor 1 pinTypeID
    // 7  = Sensor 1 pinID
    // 8  = Sensor 1 sensor name
    // 9  = Sensor 2 value
    // 10  = Sensor 2 sensor data type
    // 11  = Sensor 2 less than or greater than
    // 12  = Sensor 2 stability delay
    // 13  = Sensor 2 pinTypeID
    // 14  = Sensor 2 pinID
    // 15  = Sensor 2 sensor name
    // 16  = dashboard alert
    // 17  = email alert
    // 18  = custom rule name
    for (var c=0; c < rulesNewRule.length; c++) {  // 
        
        console.log("rulesNewRule[" + c + "] = " + rulesNewRule[c] + ", ");
    }
        
    console.log("rulesNewRuleAC         = " + rulesNewRuleAC);
    console.log("rulesNewRuleACPin      = " + rulesNewRuleACPin);
    console.log("rulesNewRuleACDelay    = " + rulesNewRuleACDelay);
    console.log("rulesNewRuleDC         = " + rulesNewRuleDC);
    console.log("rulesNewRuleDCPin      = " + rulesNewRuleDCPin);
    console.log("rulesNewRuleDCDelay    = " + rulesNewRuleDCDelay);
    console.log("rulesNewRuleDose       = " + rulesNewRuleDose);
    console.log("rulesNewRuleDosePin    = " + rulesNewRuleDosePin);
    console.log("rulesNewRuleDoseDelay  = " + rulesNewRuleDoseDelay);
    console.log("rulesNewRuleDoseSuspend = " + rulesNewRuleDoseSuspend);
    console.log("rulesNewRuleDoseML     = " + rulesNewRuleDoseML);

    var count = 5;  // count number of data chunks being sent to backend
    var equipCount = 0;  // count number of equipment being sent to backend
    for (var c=0; c < 7; c++) {count++;}  // sensor 1

    if (rulesNewRule[15] != 255) {
        for (var c=0; c < 7; c++) {count++;}  // sensor 2
    }

    for (var c=0; c < rulesNewRuleAC.length; c++) {  // 
        if (rulesNewRuleAC[c] != 255) {equipCount++; count = count+5;}
    }

    for (var c=0; c < rulesNewRuleDC.length; c++) {  // 
        if (rulesNewRuleDC[c] != 255) {equipCount++; count = count+5;}
    }

    for (var c=0; c < rulesNewRuleDose.length; c++) {  // 
        if (rulesNewRuleDose[c] != 255) {equipCount++; count = count+5;}
    }


    // var command = "120," + count + "," + rulesNewRule[18] + "," + rulesNewRule[0] + "," + rulesNewRule[16] + "," + rulesNewRule[17] + "," + rulesNewRule[1] + ",";
    //                     total pieces  name                     rule type               dashboard alert          email alert    
    var command = "120," + count + "," + rulesNewRule[18] + "," + rulesNewRule[0] + "," + rulesNewRule[16] + "," + rulesNewRule[17] + ",";

    for (var c=0; c < 6; c++) {  // sensor 1
        command += rulesNewRule[2+c] + ",";
    }

    command += rulesNewRule[1] + ",";  // Logic for 1st sensor

    if (rulesNewRule[1] != 0) {
        for (var c=0; c < 6; c++) {  // sensor 2
            command += rulesNewRule[9+c] + ",";
        }
        command += "0,";  // Logic for 2nd sensor
    }


    // command = command.slice(0, -1);  // remove last comma
    
    // console.log('command ------ ' + command);
    // sendToBackend(command);

    // command = "121," + count + ",";
    var offOnCycle = 0;

    for (var c=0; c < rulesNewRuleAC.length; c++) {  // 
        if (rulesNewRuleAC[c] != 255) {
            console.log('rulesNewRuleAC[c] ------ ' + rulesNewRuleAC[c]);
            if (rulesNewRuleAC[c] == 2) {rulesNewRuleAC[c] = 0;}  // off
            else if (rulesNewRuleAC[c] == 3) {  // on-off
                if (offOnCycle == 0) {rulesNewRuleAC[c] = 1; offOnCycle = 1;}
                else if (offOnCycle == 1) {rulesNewRuleAC[c] = 0; offOnCycle = 0;}
            }
            else if (rulesNewRuleAC[c] == 4) {  // off-on
                if (offOnCycle == 0) {rulesNewRuleAC[c] = 0; offOnCycle = 1;}
                else if (offOnCycle == 1) {rulesNewRuleAC[c] = 1; offOnCycle = 0;}
            }

            command += rulesNewRuleAC[c] + ",";  // on or off
            command += rulesNewRuleACDelay[c] + ",";  // switch delay
            command += rulesNewRuleACPin[c] + ",";  // pinID
            command += "0,";  // dose delay
            command += "0,";  // dose mL's
            console.log('rulesNewRuleAC[c] ------ ' + rulesNewRuleAC[c]);
        }
    }
    // command ------ 120,16,stop,2,0,0,1,0,0,1,8,91,0,2,0,89,0
    // command ------ 120,16,stop,2,0,0,1,0,0,1,8,91,0,0,89,0
    
    for (var c=0; c < rulesNewRuleDC.length; c++) {  // 
        if (rulesNewRuleDC[c] != 255) {
            if (rulesNewRuleDC[c] == 2) {rulesNewRuleDC[c] = 0;}  // off
            else if (rulesNewRuleDC[c] == 3) {  // on-off
                if (offOnCycle == 0) {rulesNewRuleDC[c] = 1; offOnCycle = 1;}
                else if (offOnCycle == 1) {rulesNewRuleDC[c] = 0; offOnCycle = 0;}
            }
            else if (rulesNewRuleDC[c] == 4) {  // off-on
                if (offOnCycle == 0) {rulesNewRuleDC[c] = 0; offOnCycle = 1;}
                else if (offOnCycle == 1) {rulesNewRuleDC[c] = 1; offOnCycle = 0;}
            }

            command += rulesNewRuleDC[c] + ",";  // on or off
            command += rulesNewRuleDCDelay[c] + ",";  // switch delay
            command += rulesNewRuleDCPin[c] + ",";  // pinID
            command += "0,";  // dose delay
            command += "0,";  // dose mL's
        }
    }

    for (var c=0; c < rulesNewRuleDose.length; c++) {  // 
        if (rulesNewRuleDose[c] != 255) {
            command += rulesNewRuleDose[c] + ",";  // on or off
            command += rulesNewRuleDoseDelay[c] + ",";  // switch delay
            command += rulesNewRuleDosePin[c] + ",";  // pinID
            command += rulesNewRuleDoseSuspend[c] + ",";  // dose delay
            command += rulesNewRuleDoseML[c] + ",";  // dose mL's
        }
    }
    // command += "f";  // finished

    command = command.slice(0, -1);  // remove last comma
    
    sendToBackend(command);
    console.log('command ------ ' + command);
    console.log("");
}

function confirmRule() {  // runs when backend sends command acknowledging the custom rule was added or edited
    // console.log('confirmRule --------------- ');
    getCustomRules();
}