
console.log('startup running');
var command = "998";
sendToBackend(command);
checkStartupWizard();
// update_ds18b20();
// updateProbes();
$(window).resize(function() {
    //resize just happened, pixels changed
});
$(window).resize(function() {
    if(this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function() {
        $(this).trigger('resizeEnd');
        getWindowSize();
        if (displayScreen == 0) {  // dashboard
            redrawTempWidget = 1;
            redrawDashboardCol1();
            printTemps();
            printGraphs();
        }
        else if (displayScreen == 9) {  // log screen
            printLog();
        }
    }, 500);
});

function checkStartupWizard() {  // 
    startupRunning = 1;
    $.ajax({  // check if first time running program
        url: "/php/checkStartupWizard.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {
            console.log('checkStartupWizard ----------');
            // console.log(dataWindow);
            startupWizardRunning = 0;
            userID = [];
            username = [];
            userFirstRun = [];
            adminEmail = [];
            email1 = [];
            email2 = [];
            email2Enabled = [];
            email3 = [];
            email3Enabled = [];

            for (var i = 0; i < dataWindow.length; i++){
                userID.push(dataWindow[i].userID);
                username.push(dataWindow[i].username);
                userFirstRun.push(dataWindow[i].firstRun);
                adminEmail.push(dataWindow[i].adminEmail);
                email1.push(dataWindow[i].email1);
                email2.push(dataWindow[i].email2);
                email2Enabled.push(dataWindow[i].email2Enabled);
                email3.push(dataWindow[i].email3);
                email3Enabled.push(dataWindow[i].email3Enabled);
            }
            // console.log("userID         = " + userID);
            // console.log("username       = " + username);
            // console.log("userFirstRun   = " + userFirstRun);
            // console.log("adminEmail     = " + adminEmail);
            // console.log("email1         = " + email1);
            // console.log("email2         = " + email2);
            // console.log("email2Enabled  = " + email2Enabled);
            // console.log("email3         = " + email3);
            // console.log("email3Enabled  = " + email3Enabled);
            
            if (userFirstRun == 0) {  // start startup wizard
                startupWizardRunning = 1;
                startupWizard();
                // startupSetupComplete();
            }

            // console.log("startupWizardRunning = " + startupWizardRunning);
            if (startupWizardRunning == 0) {getDriverInfo();}
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('checkStartupWizard error');
        }
    });
}
// window.mobileCheck = function() {
//     let check = false;
//     (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
//     console.log('mobileCheck');
//     console.log(check);
//     return check;
//   };
// function detectMob() {
//     const toMatch = [
//         /Android/i,
//         /webOS/i,
//         /iPhone/i,
//         /iPad/i,
//         /iPod/i,
//         /BlackBerry/i,
//         /Windows Phone/i
//     ];

//     return toMatch.some((toMatchItem) => {
//         console.log('mobileCheck');
//         console.log(navigator.userAgent.match(toMatchItem));
//         return navigator.userAgent.match(toMatchItem);
//     });
// }

// function mapOrder (array, order, key) {  // used to sort incoming json from ajex request based on another array
//     array.sort( function (a, b) {
//         var A = a[key], B = b[key];
//         if (order.indexOf(A) > order.indexOf(B)) {
//             return 1;
//         } else {
//             return -1;
//         }
//     });
//     return array;
// };

function firstTimeStartupFinished() {  // 
    console.log('firstTimeStartupFinished ----------');
    startupWizardRunning = 0;
    
    $.ajax({  // update database with ds18b20 sensor ids
        method: "POST",
        url: "/php/startupComplete.php",
        dataType: "text/plain"
    });

    getDriverInfo();
}

function getDriverInfo() {  // 
    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/getDriverData.php",
        cache: false,
        dataType: "json",
        // dataType: "text/plain",
        data: {
            "s": scheduleSortType,
            "a": scheduleSortOrder
        },
        success: function(dataWindow) {

            driverID = [];  // track driverID for each port
            portsPinID = [];  // track all pinID for each port
            roboTankPortName = [];  // portName from pinsAvailable table
            customPortName = [];  // name from pinsAvailable table
            pinTypeID = [];  // pinTypeID from pinsAvailable table
            pinTypeName = [];  // pinTypeID from pinsType table
            gpioPin = [];  // gpio from pinsAvailable table
            pinAssigned = [];  // assigned from pinsAvailable table
            driverName = [];  // driverName from drivers table
            pinIconID = [];  // iconID from pinsAvailable table
            portLogic = [];  // track if logic should be inverted
            
            for (var i = 0; i < dataWindow.length; i++){
                driverID.push(dataWindow[i].driverID);
                portsPinID.push(dataWindow[i].pinID);
                roboTankPortName.push(dataWindow[i].portName);
                customPortName.push(dataWindow[i].name);
                pinTypeID.push(dataWindow[i].pinTypeID);
                pinTypeName.push(dataWindow[i].pinTypeName);
                gpioPin.push(dataWindow[i].gpio);
                pinAssigned.push(dataWindow[i].assigned);
                driverName.push(dataWindow[i].driverName);
                pinIconID.push(dataWindow[i].iconID);
                portLogic.push(dataWindow[i].invert);
            }

            var names = {};  // object to count pins
            for (var i = 0; i < driverName.length; i++) {  // go through each driver name to find duplicates and count each set
                names[driverName[i]] = 1 + (names[driverName[i]] || 0);
                // console.log(names[driverName[i]]);
            }
            
            totalDrivers = Object.keys(names).length;

            totalDriverPins[0] = names[driverName[0]];  // first driver - Raspberry Pi
            // console.log("totalDriverPins[0] = " + totalDriverPins[0]);

            // console.log("driverName[totalDriverPins-1] = " + driverName[22]);
            // console.log("driverName[totalDriverPins-1] = " + driverName[38]);
            // console.log("driverName[totalDriverPins-1] = " + driverName[54]);
            // console.log("totalDriverPins[0] = " + names[driverName[22]]);
            // console.log("totalDriverPins[1] = " + names[driverName[38]]);
            // console.log("totalDriverPins[2] = " + names[driverName[54]]);
            // console.log("");

            var pinCount = 0;
            for (var i = 0; i < driverName.length; i++) {  // go through any extra drivers
                if (driverName[i] == driverName[0]) {pinCount++;}
            }
            // console.log("pinCount = " + pinCount);

            var arrayLoc = pinCount - 1;
            totalDriverPins[d] = names[driverName[arrayLoc]];  // first driver - Raspberry Pi
            // console.log("arrayLoc = " + arrayLoc);
            for (var d = 1; d < totalDrivers; d++) {  // go through any extra drivers
                var pinCount2 = 0;
                for (var i = 0; i < driverName.length; i++) {  // go through any extra drivers
                    if (driverName[i] == driverName[arrayLoc+1]) {pinCount2++;}
                }
                arrayLoc = arrayLoc + pinCount2;
                totalDriverPins[d] = names[driverName[arrayLoc]];  // first driver - Raspberry Pi

                // console.log("pinCount2 = " + pinCount2);
                // console.log("arrayLoc = " + arrayLoc);

            }

            // var arrayLoc = 22;
            // for (var i = 0; i < totalDrivers; i++) {  // go through any extra drivers
            //     // totalDriverPins[i+1] = names[driverName[totalDriverPins[i]]];  // get total pins for each driver
            //     totalDriverPins[i] = names[driverName[arrayLoc]];  // first driver - Raspberry Pi
            //     if (arrayLoc > 0) arrayLoc = arrayLoc + totalDriverPins[i];
            //     console.log("totalDriverPins[i] = " + totalDriverPins[i]);
            //     console.log("arrayLoc = " + arrayLoc);
            // }

            console.log("getDriverInfo--------------------------------------------------------------");
            // console.log(driverID);
            // console.log(names);
            // console.log(names["Raspberry Pi"]);
            // console.log(names["PCA9685"]);
            // console.log(names["pca2"]);
            // console.log(names[driverName[0]]);
            // console.log(names[driverName[23]]);
            // console.log("totalDrivers = " + totalDrivers);
            // console.log("totalDriverPins = " + totalDriverPins);
            // console.log(portsPinID);
            // for (var d = 0; d < roboTankPortName.length; d++) {  // go through any extra drivers
            //     console.log(d + " - " + roboTankPortName[d]);
            // }
            // console.log(customPortName);
            // console.log(pinTypeID);
            // console.log(pinTypeName);
            // console.log(gpioPin);
            // console.log(pinAssigned);
            // console.log(driverName);
            // console.log(pinIconID);
            // console.log(portLogic);
            
            if (startupRunning == 1) {
                getSystemSettings();
            }
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getDriverInfo');
        }
    });
}

function getSystemSettings() {  // 
    $.ajax({  // get system settings
        url: "/php/getSystemSettings.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {
            console.log("getSystemSettings--------------------------------------------------------------");
            // console.log(dataWindow);
            configPortView = (dataWindow[0].configView);
            db9_1 = (dataWindow[0].db9_1);
            db9_2 = (dataWindow[0].db9_2);
            tempCorF = (dataWindow[0].tempCorF);
            timeFormat = (dataWindow[0].timeFormat);
            outletSortID = (dataWindow[0].outletSortID);
            dcSortID = (dataWindow[0].dcSortID);
            scheduleTabSelected = (dataWindow[0].scheduleTabSelected);
            scheduleSortID = (dataWindow[0].scheduleSortID);
            scheduleSortOrder = (dataWindow[0].scheduleSortOrder);
            emailEnabled = (dataWindow[0].emailEnabled);  // track if email alerts are enabled
            smtpServer = (dataWindow[0].smtpServer);  // SMTP server
            smtpPort = (dataWindow[0].smtpPort);  // SMTP port
            smtpUser = (dataWindow[0].smtpUser);  // SMTP user
            smtpPass = (dataWindow[0].smtpPass);  // SMTP password
            smtpProvider = (dataWindow[0].smtpProvider);  // SMTP provider
            autoUpdate = (dataWindow[0].autoUpdate);  // auto updated enabled/disabled
            appVersion = (dataWindow[0].version);  // version running
            controllerVersion = (dataWindow[0].controllerVersion);  // controller version
            latestVersion = (dataWindow[0].versionLatest);  // latest version
            supportID = (dataWindow[0].supportID);  // supportID

            
            // console.log('emailEnabled   = ' + emailEnabled);
            // console.log('appVersion     = ' + appVersion);
            // console.log('latestVersion  = ' + latestVersion);
            // console.log('autoUpdate     = ' + autoUpdate);
            // console.log('supportID      = ' + supportID);
            // console.log('smtpProvider   = ' + smtpProvider);
                
            if (scheduleSortID == 1) {scheduleSortType = "type"}
            else if (scheduleSortID == 2) {scheduleSortType = "schName"}
            else if (scheduleSortID == 3) {scheduleSortType = "start"}
            else if (scheduleSortID == 4) {scheduleSortType = "offOn"}
            else if (scheduleSortID == 5) {scheduleSortType = "mon"}
            else if (scheduleSortID == 6) {scheduleSortType = "tue"}
            else if (scheduleSortID == 7) {scheduleSortType = "wed"}
            else if (scheduleSortID == 8) {scheduleSortType = "thu"}
            else if (scheduleSortID == 9) {scheduleSortType = "fri"}
            else if (scheduleSortID == 10) {scheduleSortType = "sat"}
            else if (scheduleSortID == 11) {scheduleSortType = "sun"}
            else if (scheduleSortID == 12) {scheduleSortType = "enabled"}
            else if (scheduleSortID == 13) {scheduleSortType = "schEmail"}
            else if (scheduleSortID == 14) {scheduleSortType = "schAlert"}
            else if (scheduleSortID == 15) {scheduleSortType = "name"}
            else if (scheduleSortID == 16) {scheduleSortType = "mL"}
            // console.log("scheduleSortType  = " + scheduleSortType); 
            // console.log("scheduleSortOrder = " + scheduleSortOrder);
            
            if (startupRunning == 1) {getButtonLabels();}
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error');
        }
    });
}

function getButtonLabels() {  // 
    $.ajax({  // get button labels
        url: "/php/getButtonLabels.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {
            // console.log(dataWindow);
            console.log("getButtonLabels--------------------------------------------------------------");
            buttonID = [];
            buttonLabels = [];
            for (var i = 0; i < dataWindow.length; i++){
                buttonID.push(dataWindow[i].buttonID);
                buttonLabels.push(dataWindow[i].label);
            }
            if (startupRunning == 1) {getDS18B20();}
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error');
        }
    });
}

function getDS18B20(){  // continually update sensor data from database
    $.ajax({  // get ds18b20 sensor names
        url: "/php/ds18b20Read.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) 
        {
            // console.log('getDs18b20Data3.........................................');
            // console.log(dataWindow);

            // console.log(previousDs18b20Found);
            // console.log(ds18b20Found);
            // console.log(ds18b20AddrFound);
            previousDs18b20Found = ds18b20Found;   // store number of sensors found before reading sensor data so we know if one was plugged in
            var ds18b20Plugged = [];  // clear ds18b20Plugged
            ds18b20Name = [];  // all custom names in database
            ds18b20AddrSaved = [];  // all ds18b20 internal IDs in database
            ds18b20GraphVisible = [];  // tracks if graph is visible in widget
            ds18b20GraphRange = [];  // track time frame being viewed in graph
            ds18b20GraphAverage = [];  // track rolling average of graph
            ds18b20AddrFound = [];  // ds18b20 internal ID of sensors plugged in
            ds18b20NamePlugged = [];  // custom names of sensors plugged in
            // ds18b20Temp = [];  // clear temps
            // ds18b20Min = [];  // clear min
            // ds18b20Max = [];  // clear max
            ds18b20Found = 0;  // reset how many ds18b20 sensors are seen
            ds18b20Saved = 0;  // tracks how many sensors are in database

            for(var i in dataWindow) 
            {
                // get data for all sensors in database
                ds18b20Plugged.push(dataWindow[i].plugged);  // tracks if sensor is plugged in or not
                ds18b20Name.push(dataWindow[i].name);  // custom name
                // console.log("isThisANumber" + isThisANumber(dataWindow[i].address));
                ds18b20AddrSaved.push(dataWindow[i].address);  // ds18b20 internal ID
                // if (isThisANumber(dataWindow[i].address) == false) {ds18b20AddrSaved.push(dataWindow[i].address);}  // ds18b20 internal ID
                // else {ds18b20AddrSaved.push(dataWindow[i].address); ds18b20AddrSaved[i] = "dht_" + ds18b20AddrSaved[i]}  // ds18b20 internal ID
                ds18b20GraphVisible.push(dataWindow[i].graphVisible);  // tracks if graph is visible in widget
                ds18b20GraphRange.push(dataWindow[i].graphRange);
                ds18b20GraphAverage.push(dataWindow[i].graphAverage);

                if (ds18b20Plugged[i] == 1)  // get send data only for plugged in sensors
                {
                    ds18b20AddrFound.push(dataWindow[i].address);  // ds18b20 internal ID
                    ds18b20NamePlugged.push(dataWindow[i].name);  // custom names
                    // ds18b20Temp.push(dataWindow[i].temp);  // record ds18b20 temps
                    // ds18b20Min.push(dataWindow[i].min);  // record ds18b20 min
                    // ds18b20Max.push(dataWindow[i].max);  // record ds18b20 max
                    ds18b20Found++;  // tracks how many sensors are plugged in
                }
                ds18b20Saved++;  // tracks how many sensors are in database
            }
            redrawTempWidget = 1;
            if (startupRunning == 1) {getProbes();}
            // console.log("redrawTempWidget");
            // console.log(ds18b20AddrSaved);
            // console.log(previousDs18b20Found);
            // console.log(ds18b20Found);
            // console.log(ds18b20Max);
        },
        error: function(dataWindow) {
            console.log('ERROR - reading database ds18b20 -----------------------------------------------------------------');
            console.log(dataWindow);// no sensor data
            
        }
    });
}

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

    $.ajax({  // get info for all probes
        url: "/php/phRead.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) 
        {
            // console.log(dataWindow);
            previousPhFound = phSeen;   // store number of sensors found before reading sensor data so we know if one was plugged in
            phPlugged = [];
            phName = [];
            phGraphVisible = [];
            phGraphRange = [];
            phGraphAverage = [];  // track rolling average of graph
            phNamePlugged = [];
            phAddrSaved = [];
            phAddrPlugged = [];
            // phValue = [];
            // phMinValue = [];
            // phMaxValue = [];
            phSeen = 0;  // reset how many sensors are seen
            phSaved = 0;  // tracks how many sensors are in database

            for(var i in dataWindow) 
            {
                phPlugged.push(dataWindow[i].plugged);  // track if sensor is plugged in or not for table
                phName.push(dataWindow[i].name);
                phAddrSaved.push(dataWindow[i].address);  // get all addresses in database for table
                phGraphVisible.push(dataWindow[i].graphVisible);
                phGraphRange.push(dataWindow[i].graphRange);
                phGraphAverage.push(dataWindow[i].graphAverage);
                if (phPlugged[i] == 1)  // get custom names for only plugged in sensors
                {
                    phAddrPlugged.push(dataWindow[i].address);
                    phNamePlugged.push(dataWindow[i].name);
                    phCalibrateRunning[phSeen] = 0;
                    // phValue.push(dataWindow[i].value);
                    // phMinValue.push(dataWindow[i].min);
                    // phMaxValue.push(dataWindow[i].max);
                    phSeen++;  // tracks how many sensors are plugged in
                }
                phSaved++;  // track how many sensors are in the database

            }
            redrawProbesWidget = 1;
            if (startupRunning == 1) {getListOfOutlets();}
            console.log('getProbes() -----------------------------------------------------------------');
            // console.log(redrawProbesWidget);
            // console.log(phNamePlugged);
            // console.log(previousPhFound);
            // console.log(phSeen);
            // console.log(phMaxValue);
            // console.log("");
        },
        error: function(dataWindow) {
            console.log('ERROR - getProbes() -----------------------------------------------------------------');
            console.log(dataWindow);// no sensor data
            
        }
    });
}

function getListOfOutlets() {  // get list of outlets
    $.ajax({
        url: "/php/acGetOutlets.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {

            console.log("getListOfOutlets--------------------------------------------------------------");
            outletPinID = [];
            outletGpioPinNumber = [];
            outletName = [];
            outletAssigned = [];
            outletIconID = [];
            outletInvert = [];
            outletManual = [];  // track if outlet is in manual mode

            for(var i in dataWindow) {
                outletPinID[i] = (dataWindow[i].pinID);
                outletGpioPinNumber[i] = (dataWindow[i].gpio);
                outletName[i] = (dataWindow[i].name);
                outletAssigned[i] = (dataWindow[i].assigned);
                outletIconID[i] = (dataWindow[i].iconID);
                outletInvert[i] = (dataWindow[i].invert);
                outletManual[i] = (dataWindow[i].manual);
            }
            
            // console.log("outletPinID  = " + outletPinID);
            // console.log("outletManual = " + outletManual);
            if (startupRunning == 1) {getListOfDc();}
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getListOfOutlets');
        }
    });
}
function getListOfDc(){  // get list of DC ports
    $.ajax({
        url: "/php/dcGetPorts.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {

            console.log("getListOfDc--------------------------------------------------------------");
            dcPinID = [];
            dcGpioPinNumber = [];
            dcName = [];
            dcAssigned = [];
            dcIconID = [];
            dcInvert = [];
            dcManual = [];  // track if DC port is in manual mode

            for(var i in dataWindow) {
                dcPinID[i] = (dataWindow[i].pinID);
                dcGpioPinNumber[i] = (dataWindow[i].gpio);
                dcName[i] = (dataWindow[i].name);
                dcAssigned[i] = (dataWindow[i].assigned);
                dcIconID[i] = (dataWindow[i].iconID);
                dcInvert[i] = (dataWindow[i].invert);
                dcManual[i] = (dataWindow[i].manual);
            }
            
            if (startupRunning == 1) {getListOfSensors();}
            // console.log("dcPinID  = " + dcPinID);
            // console.log("dcManual = " + dcManual);
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getListOfDc');
        }
    });
}
function getListOfSensors() {  // get list of outlets
    $.ajax({
        url: "/php/sensorsGetList.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {

            sensorPinID = [];  // sensor pin ID from pinsAvailable table
            sensorGpioPinNumber = [];  // sensor pigpio library pin number
            sensorName = [];  // sensor name
            sensorTypeID = [];  // sensor pinTypeID
            sensorTypeName = [];  // sensor type name
            sensorAssigned = [];  // track if outlet is assigned/enabled 
            sensorIconID = [];  // sensor icon
            sensorInvert = [];  // track if sensor logic is inverted

            for(var i in dataWindow) {
                sensorPinID[i] = (dataWindow[i].pinID);
                sensorGpioPinNumber[i] = (dataWindow[i].gpio);
                sensorName[i] = (dataWindow[i].name);
                sensorTypeID[i] = (dataWindow[i].pinTypeID);
                sensorTypeName[i] = (dataWindow[i].pinTypeName);
                sensorAssigned[i] = (dataWindow[i].assigned);
                sensorIconID[i] = (dataWindow[i].iconID);
                sensorInvert[i] = (dataWindow[i].invert);
            }
            
            console.log("getListOfSensors--------------------------------------------------------------");
            if (startupRunning == 1) {getListOfLights();}
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getListOfSensors');
        }
    });
}
function getListOfLights(){  // get list of light port type
    $.ajax({
        url: "/php/lightPorts.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {
            lightPinID = [];
            lightName = [];
            lightAssigned = [];
            lightIconID = [];

            for(var i in dataWindow) {
                lightPinID[i] = (dataWindow[i].pinID);
                lightName[i] = (dataWindow[i].name);
                lightAssigned[i] = (dataWindow[i].assigned);
                lightIconID[i] = (dataWindow[i].iconID);
            }
            console.log("getListOfLights--------------------------------------------------------------");
            if (startupRunning == 1) {getLightModes();}
            // console.log(lightPinID);
            // console.log(lightName);
            // console.log(lightAssigned);
            // console.log(lightIconID);
            
            // printLightWidget();
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getListOfLights');
        }
    });
}

function getLightModes(){  // get list of light modes
    $.ajax({
        url: "/php/getLightModeDetails.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {

            console.log("getLightModes--------------------------------------------------------------");
            lightModeID = [];
            lightModePinID = [];
            lightModeStartLevel = [];
            lightModeStart = [];
            lightModeEnabled = [];

            for (var i = 0; i < dataWindow.length; i++){
                lightModeID.push(dataWindow[i].modeID);
                lightModePinID.push(dataWindow[i].pinID);
                lightModeStart.push(dataWindow[i].start);
                lightModeStartLevel.push(dataWindow[i].startLevel);
                lightModeEnabled.push(dataWindow[i].enabled);
            }
            if (startupRunning == 1) {getSchedules();}
            if (updatingUI == 1) {
                viewLightModes();
                updatingUI = 0;
            }
            
            // console.log(dataWindow);
            // console.log(lightDetailModeID);
            // console.log(lightModePinID);
            // console.log(lightModeStart);
            // console.log(lightModeEnd);
            // console.log(lightModeStartLevel);
            // console.log(lightModeEndLevel);
            // printLightWidget();
        },
        error: function(dataWindow) {
            console.log('error - getLightModes');
            console.log(dataWindow);
        }
    });
}

function getSchedules(){  // get list of light modes
    // $.ajax({
    //     url: "/php/schedulesGetData.php",
    //     method: "GET",
    //     cache: false,
            // console.log("scheduleSortType   = " + scheduleSortType);
            // console.log("scheduleSortOrder  = " + scheduleSortOrder);
    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/schedulesSort.php",
        cache: false,
        dataType: "json",
        // dataType: "text/plain",
        data: {
            "s": scheduleSortType,
            "a": scheduleSortOrder
        },
        success: function(dataWindow) {

            scheduleID = [];
            scheduleTypeID = [];  // track what the schedule is for
            schedulePinID = [];  // track pinID from pinsAvailable table
            scheduleStart = [];  // track schedule start time in seconds
            scheduleMon = [];  // track if mon enabled
            scheduleTue = [];  // track if tue enabled
            scheduleWed = [];  // track if wed enabled
            scheduleThu = [];  // track if thu enabled
            scheduleFri = [];  // track if fri enabled
            scheduleSat = [];  // track if sat enabled
            scheduleSun = [];  // track if sun enabled
            scheduleRepeatEnabled = [];  // track if schedule repeats X number of days
            scheduleRepeatDays = [];  // track if schedule is repeated and how often in days
            scheduleOffOn = [];  // track if schedule is on or off
            scheduleName = [];  // track schedule custom name
            scheduleEquipmentName = [];  // track name of equipment for schedule
            scheduleEquipmentIconID = [];  // track iconID of equipment for schedule
            scheduleEnabled = [];  // track if scheduled is enabled
            scheduleEmail = [];  // track if email alert is enabled
            scheduleAlert = [];  // track if dashboard alert is enabled
            scheduleType = [];  // track schedule type name
            scheduleDoseML = [];  // track how many milliliters are attached to schedule
            
            for (var i = 0; i < dataWindow.length; i++){
                scheduleID.push(dataWindow[i].scheduleID);
                scheduleTypeID.push(dataWindow[i].scheduleTypeID);
                schedulePinID.push(dataWindow[i].pinID);
                scheduleOffOn.push(dataWindow[i].offOn);
                scheduleName.push(dataWindow[i].schName);
                scheduleStart.push(dataWindow[i].start);
                scheduleMon.push(dataWindow[i].mon);
                scheduleTue.push(dataWindow[i].tue);
                scheduleWed.push(dataWindow[i].wed);
                scheduleThu.push(dataWindow[i].thu);
                scheduleFri.push(dataWindow[i].fri);
                scheduleSat.push(dataWindow[i].sat);
                scheduleSun.push(dataWindow[i].sun);
                scheduleRepeatDays.push(dataWindow[i].repeatDays);
                scheduleEquipmentName.push(dataWindow[i].name);
                scheduleEquipmentIconID.push(dataWindow[i].iconID);
                scheduleEnabled.push(dataWindow[i].enabled);
                scheduleEmail.push(dataWindow[i].schEmail);
                scheduleAlert.push(dataWindow[i].schAlert);
                scheduleType.push(dataWindow[i].type);
                scheduleDoseML.push(dataWindow[i].mL);
                if (scheduleRepeatDays[i] == 0) {scheduleRepeatEnabled[i] = 0;}
                else {scheduleRepeatEnabled[i] = 1;}
            }
            

            console.log("getSchedules--------------------------------------------------------------");
            // console.log(dataWindow);
            // console.log(scheduleID);
            // console.log(scheduleTypeID);
            // console.log(scheduleOffOn);
            // console.log(scheduleName);
            // console.log(scheduleStart);
            // console.log(scheduleMon);
            // console.log(scheduleTue);
            // console.log(scheduleWed);
            // console.log(scheduleThu);
            // console.log(scheduleFri);
            // console.log(scheduleSat);
            // console.log(scheduleSun);
            // console.log(scheduleRepeatEnabled);
            // console.log(scheduleRepeatDays);
            // console.log(scheduleEquipmentName);
            // console.log(scheduleEquipmentIconID);
            // console.log(scheduleEnabled);
            // console.log(scheduleEmail);
            // console.log(scheduleAlert);
            // console.log(scheduleType);
            if (startupRunning == 1) {getDosingPumps();}
            else {  // update schedule list
                if (prevDisplayScreen == 10) {dosingSettings();}  // if viewing dosing settings return 
                else {printSchedulesTableMenu(scheduleTabSelected);}
            }
        },
        error: function(dataWindow) {
            console.log("scheduleSortType 2  = " + scheduleSortType);
            console.log("scheduleSortOrder 2 = " + scheduleSortOrder);
            console.log(dataWindow);
            console.log('error - getSchedules');
        }
    });
}

function getDosingPumps(){  // get list of dosing pumps
    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/dosingGetPumps.php",
        cache: false,
        dataType: "json",
        // dataType: "text/plain",
        data: {
            "s": scheduleSortType,
            "a": scheduleSortOrder
        },
        success: function(dataWindow) {

            doseID = [];  // track dosing pump ID
            dosePinID = [];  // track dosing pump pinID from pinsAvailable table
            doseStirrerID = [];  // track what stirrer is connected to dosing pump
            doseName = [];  // track dosing pump custom name
            doseAmount = [];  // stores dose amount in ml
            doseReservoirSize = [];  // stores reservoir size in ml
            doseReservoirRemain = [];  // stores remaining space in reservoir in ml
            doseReservoirColor = [];  // track custom reservoir color
            dosePumpRate = [];  // stores pump rate in ms/ml
            doseStirrer = [];  // stores if stirrer is enabled
            stirrerRuntime = [];  // track how long stirrer should run in seconds
            settlingRuntime = [];  // track how long reservoir should settle after stirring in seconds
            stirrerSpeed = [];  // track speed of stirrer
            doseStepRunning = [];  // tracks which step the system is in during the dosing process
            doseRunTime = [];  // stores how long pump should run in millis
            doseCalibrationAmount = [];  // tracks dose amount used for calibrating vessel
            doseCalibrateRunning = [];  // tracks is calibration is running
            doseInterval = [];  // track the minimum period between doses in minutes
            doseDisableRes = [];  // track if reservoir is disabled
            dosePumpSpeed = [];  // track speed of dosing pump
            doseResAlert = [];  // track if dashboard alert is enabled
            doseResEmail = [];  // track if email alert is enabled
            doseResAlertML = [];  // track level to be alert on low reservoir
            
            for (var i = 0; i < dataWindow.length; i++){
                doseID.push(dataWindow[i].doseID);
                dosePinID.push(dataWindow[i].dosePinID);
                doseStirrerID.push(dataWindow[i].doseStirrerID);
                doseName.push(dataWindow[i].doseName);
                doseAmount[i] = 0;
                doseRunTime[i] = 0;
                doseReservoirRemain.push(dataWindow[i].reservoirRemain);
                doseReservoirSize.push(dataWindow[i].reservoirSize);
                doseReservoirColor.push(dataWindow[i].reservoirColor);
                dosePumpRate.push(dataWindow[i].dosePumpRate);
                doseStirrer.push(dataWindow[i].doseStirrer);
                stirrerRuntime.push(dataWindow[i].stirrerRuntime);
                settlingRuntime.push(dataWindow[i].settlingRuntime);
                stirrerSpeed.push(dataWindow[i].stirrerSpeed);
                stirrerSpeed[i] = round((stirrerSpeed[i] / 4095) * 100, 1).toFixed(0);
                doseCalibrationAmount.push(dataWindow[i].calibrateAmount);
                doseInterval.push(dataWindow[i].doseInterval);
                doseDisableRes.push(dataWindow[i].disableRes);
                dosePumpSpeed.push(dataWindow[i].pumpSpeed);
                dosePumpSpeed[i] = round((dosePumpSpeed[i] / 4095) * 100, 1).toFixed(0);
                doseResAlert.push(dataWindow[i].resAlert);
                doseResEmail.push(dataWindow[i].resEmail);
                doseResAlertML.push(dataWindow[i].resAlertML);
                // calculate how long pumps should run in milliseconds
                // doseRunTime[i] = dosePumpRate[i] * doseAmount[i];  
            }
            
            console.log("getDosingPumps--------------------------------------------------------------");
            // console.log(dataWindow);
            // console.log(doseID);
            // console.log(dosePinID);
            // console.log(doseStirrerID);
            // console.log(doseName);
            // console.log(doseAmount);
            // console.log(doseReservoirRemain);
            // console.log(doseReservoirSize);
            // console.log(doseReservoirColor);
            // console.log(dosePumpRate);
            // console.log(doseStirrer);
            // console.log(stirrerRuntime);
            // console.log(settlingRuntime);
            // console.log(stirrerSpeed);
            // console.log(doseCalibrationAmount);
            // console.log(doseInterval);
            // console.log(doseDisableRes);
            // console.log(dosePumpSpeed);
            // console.log(doseResAlert);
            // console.log(doseResEmail);
            // console.log(doseResAlertML);
            // console.log(doseRunTime);
            // if (startupRunning == 1) {drawTemplate();}
            if (startupRunning == 1) {
                getStirrers();
            }
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getDosingPumps');
        }
    });
}

function getStirrers(){  // get list of dosing pumps
    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/dosingGetStirrers.php",
        cache: false,
        dataType: "json",
        success: function(dataWindow) {

            stirrerID = [];  // track dosing pump ID
            stirrerPinID = [];  // track dosing pump pinID from pinsAvailable table
            stirrerName = [];  // track stirrer custom name
            
            for (var i = 0; i < dataWindow.length; i++){
                stirrerID.push(dataWindow[i].stirrerID);
                stirrerPinID.push(dataWindow[i].stirrerPinID);
                stirrerName.push(dataWindow[i].name)
            }
            
            console.log("getStirrers--------------------------------------------------------------");
            // console.log(dataWindow);
            // console.log(stirrerID);
            // console.log(stirrerPinID);
            // console.log(stirrerName);
            if (startupRunning == 1) {
                getCustomRules();
            }
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getStirrers');
        }
    });
}

function getCustomRules(){  // get list of dosing pumps
    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/rulesGetList.php",
        cache: false,
        dataType: "json",
        // dataType: "text/plain",
        success: function(dataWindow) {

            ruleID = [];  // track ruleID
            rulesName = [];  // track rule name
            rulesTypeID = [];  // track ruleTypeID, schedule, sensor or manual
            rulesType = [];  // track rule type, schedule, sensor or manual
            rulesEmail = [];  // track if email is enabled
            rulesAlert = [];  // track if dashboard alert is enabled
            rulesEnabled = [];  // track if rule is enabled
            
            for (var i = 0; i < dataWindow.length; i++){
                ruleID.push(dataWindow[i].ruleID);
                rulesName.push(dataWindow[i].ruleName);
                rulesTypeID.push(dataWindow[i].ruleTypeID);
                rulesType.push(dataWindow[i].ruleType);
                rulesEmail.push(dataWindow[i].email);
                rulesAlert.push(dataWindow[i].alert);
                rulesEnabled.push(dataWindow[i].enabled);
            }
            
            console.log("getCustomRules--------------------------------------------------------------");
            // console.log(dataWindow);
            // console.log(ruleID);
            // console.log(rulesName);
            // console.log(rulesTypeID);
            // console.log(rulesType);
            // console.log(rulesEmail);
            // console.log(rulesAlert);
            // console.log(rulesEnabled);
            // if (startupRunning == 1) {
            //     getCustomRuleSensors();
            // }
            getCustomRuleSensors();
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getCustomRules');
        }
    });
}

function getCustomRuleSensors(){  // get list of dosing pumps
    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/rulesGetListSensors.php",
        cache: false,
        dataType: "json",
        // dataType: "text/plain",
        success: function(dataWindow) {

            rulesSensorRuleID = [];  // track ruleID
            rulesSensorAddress = [];  // track sensorAddress for rule sensors
            rulesSensorPinID = [];  // track pinID for rule sensors
            rulesSensorPinTypeID = [];  // track what kind of sensor it is
            rulesSensorName = [];  // track custom name of sensor
            rulesSensorDataType = [];  // track what data from sensor is used in rule
            rulesSensorValue = [];  // track sensor trigger value
            rulesSensorLessGreater = [];  // track if less than or greater than
            rulesSensorStability = [];  // track how long the sensor should remain in trigger zone before triggering, in seconds
            rulesSensorLogic = [];  // track if sensor works with another, None, AND, OR
            
            for (var i = 0; i < dataWindow.length; i++){
                rulesSensorRuleID.push(dataWindow[i].ruleID);
                rulesSensorAddress.push(dataWindow[i].sensorAddress);
                rulesSensorDataType.push(dataWindow[i].sensorDataType);
                if (dataWindow[i].sensorPinID == null) {rulesSensorPinID.push(dataWindow[i].sensorAddress);}
                else {rulesSensorPinID.push(dataWindow[i].sensorPinID);}

                // console.log("dataWindow[i].name  = " + dataWindow[i].name);
                // console.log("dataWindow[i].name2 = " + dataWindow[i].name2);
                // console.log("dataWindow[i].name3 = " + dataWindow[i].name3);
                // console.log("----------- ");

                if ((dataWindow[i].name == null) && (dataWindow[i].name3 == null)) {rulesSensorName.push(dataWindow[i].name2);}  // ds18b20 / dht22
                else if ((dataWindow[i].name == null) && (dataWindow[i].name2 == null)) {rulesSensorName.push(dataWindow[i].name3);}  // ph probes
                else if ((dataWindow[i].name2 == null) && (dataWindow[i].name3 == null)) {rulesSensorName.push(dataWindow[i].name);}  // gpio sensors

                if ((dataWindow[i].pinTypeID == null) && (isThisANumber(dataWindow[i].sensorAddress) == false)) {  // ds18b20 sensor
                    // console.log("Not a number");
                    // console.log(dataWindow[i].sensorAddress);
                    rulesSensorPinTypeID.push("5");
                }
                else if (dataWindow[i].pinTypeID == null) {rulesSensorPinTypeID.push("3");}  // i2c probe
                else {rulesSensorPinTypeID.push(dataWindow[i].pinTypeID);}  // Pi GPIO

                rulesSensorValue.push(dataWindow[i].sensorValue);
                rulesSensorLessGreater.push(dataWindow[i].lessGreater);
                rulesSensorStability.push(dataWindow[i].stabilitySeconds);
                rulesSensorLogic.push(dataWindow[i].logic);
            }
            
            console.log("getCustomRuleSensors--------------------------------------------------------------");
            // console.log(dataWindow);
            // console.log(rulesSensorRuleID);
            // console.log(rulesSensorAddress);
            // console.log(rulesSensorPinID);
            // console.log(rulesSensorPinTypeID);
            // console.log(rulesSensorName);
            // console.log(rulesSensorDataType);
            // console.log(rulesSensorValue);
            // console.log(rulesSensorLessGreater);
            // console.log(rulesSensorStability);
            // console.log(rulesSensorLogic);
            // if (startupRunning == 1) {
            //     getCustomRuleEquipment();
            // }
            getCustomRuleEquipment();
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getCustomRuleSensors');
        }
    });
}

function getCustomRuleEquipment() {  // get list of dosing pumps
    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/rulesGetListEquipment.php",
        cache: false,
        dataType: "json",
        // dataType: "text/plain",
        success: function(dataWindow) {

            rulesEquipRuleID = [];  // track ruleID
            rulesEquipPinID = [];  // track pinID for rule equipment
            rulesEquipPinTypeID = [];  // track pinTypeID for rule equipment
            rulesEquipIconID = [];  // track iconID for rule equipment
            rulesEquipName = [];  // track custom name of equipment
            rulesEquipOffOn = [];  // track if it turns equipment on/off
            rulesEquipSwitchDelay = [];  // track how long until device is switched on or off
            rulesEquipNextDoseDelay = [];  // track how long to delay dosing regular schedule
            rulesEquipDoseML = [];  // track how much to dose for each custom rule
            
            for (var i = 0; i < dataWindow.length; i++){
                rulesEquipRuleID.push(dataWindow[i].ruleID);
                rulesEquipPinID.push(dataWindow[i].equipmentPinID);
                rulesEquipPinTypeID.push(dataWindow[i].pinTypeID);
                rulesEquipIconID.push(dataWindow[i].iconID);
                rulesEquipName.push(dataWindow[i].name);
                rulesEquipOffOn.push(dataWindow[i].equipmentOffOn);
                rulesEquipSwitchDelay.push(dataWindow[i].switchDelay);
                rulesEquipNextDoseDelay.push(dataWindow[i].nextDoseDelay);
                rulesEquipDoseML.push(dataWindow[i].doseML);
                // if (rulesEquipNextDoseDelay[i] == 0) {  // no dose delay set in rule so grab default value
                //     for (var i = 0; i < dataWindow.length; i++){
                //     }
                // }
            }
            
            console.log("getCustomRuleEquipment--------------------------------------------------------------");
            // console.log(dataWindow);
            // console.log(rulesEquipRuleID);
            // console.log(rulesEquipPinID);
            // console.log(rulesEquipPinTypeID);
            // console.log(rulesEquipIconID);
            // console.log(rulesEquipName);
            // console.log(rulesEquipOffOn);
            // console.log(rulesEquipSwitchDelay);
            // console.log(rulesEquipNextDoseDelay);
            // console.log(rulesEquipDoseML);
            if (startupRunning == 1) {
                getVersionLog();
            }
            else if (displayScreen == 12) {customRulesList();}  // if viewing dosing settings return   // update schedule list
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getCustomRuleEquipment');
        }
    });
}

function getVersionLog(){  // get version log
    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/getVersionLog.php",
        cache: false,
        dataType: "json",
        success: function(dataWindow) {

            versionID = [];  // version ID
            version = [];  // version number
            versionDate = [];  // version date release
            
            for (var i = 0; i < dataWindow.length; i++){
                versionID.push(dataWindow[i].versionID);
                version.push(dataWindow[i].version);
                versionDate.push(dataWindow[i].versionDate);
            }
            
            console.log("getVersionLog--------------------------------------------------------------");
            // console.log(dataWindow);
            // console.log(version);
            // console.log(versionDate);
            if (startupRunning == 1) {loadGraphSettings();}
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getVersionLog');
        }
    });
}

function loadGraphSettings() {  // 
    console.log("loadGraphSettings--------------------------------------------------------------");
    var graphID = 0;
    for (var i = 0; i < ds18b20Saved; i++) {  // mark checkbox checked if needed
        graphVisible[graphID] = ds18b20GraphVisible[i];
        graphAverage[graphID] = ds18b20GraphAverage[i];
        if (ds18b20GraphRange[i] == 0) {graphDays[graphID] = 1; graphHours[graphID] = 1; graphRange[graphID] = 0;}
        else if (ds18b20GraphRange[i] == 1) {graphDays[graphID] = 1; graphHours[graphID] = 6; graphRange[graphID] = 1;}
        else if (ds18b20GraphRange[i] == 2) {graphDays[graphID] = 1; graphHours[graphID] = 24; graphRange[graphID] = 2;}
        else if (ds18b20GraphRange[i] == 3) {graphDays[graphID] = 3; graphHours[graphID] = 24; graphRange[graphID] = 3;}
        else if (ds18b20GraphRange[i] == 4) {graphDays[graphID] = 7; graphHours[graphID] = 24; graphRange[graphID] = 4;}
        else if (ds18b20GraphRange[i] == 5) {graphDays[graphID] = 14; graphHours[graphID] = 24; graphRange[graphID] = 5;}
        else if (ds18b20GraphRange[i] == 6) {graphDays[graphID] = 30; graphHours[graphID] = 24; graphRange[graphID] = 6;}
        else if (ds18b20GraphRange[i] == 7) {graphDays[graphID] = 90; graphHours[graphID] = 24; graphRange[graphID] = 7;}
        graphID++;
    }
    
    for (var i = 0; i < phSaved; i++) {  // mark checkbox checked if needed
        graphVisible[graphID] = phGraphVisible[i];
        graphAverage[graphID] = phGraphAverage[i];

        if (phGraphRange[i] == 0) {graphDays[graphID] = 1; graphHours[graphID] = 1; graphRange[graphID] = 0;}
        else if (phGraphRange[i] == 1) {graphDays[graphID] = 1; graphHours[graphID] = 6; graphRange[graphID] = 1;}
        else if (phGraphRange[i] == 2) {graphDays[graphID] = 1; graphHours[graphID] = 24; graphRange[graphID] = 2;}
        else if (phGraphRange[i] == 3) {graphDays[graphID] = 3; graphHours[graphID] = 24; graphRange[graphID] = 3;}
        else if (phGraphRange[i] == 4) {graphDays[graphID] = 7; graphHours[graphID] = 24; graphRange[graphID] = 4;}
        else if (phGraphRange[i] == 5) {graphDays[graphID] = 14; graphHours[graphID] = 24; graphRange[graphID] = 5;}
        else if (phGraphRange[i] == 6) {graphDays[graphID] = 30; graphHours[graphID] = 24; graphRange[graphID] = 6;}
        else if (phGraphRange[i] == 7) {graphDays[graphID] = 90; graphHours[graphID] = 24; graphRange[graphID] = 7;}
        graphID++;
    }

        // console.log('graphRange[0]  = ' + graphRange);
        // console.log('graphDays[0]   = ' + graphDays);
        // console.log('graphHours[0]  = ' + graphHours);

    // if (graphDays[0] == null) {graphDays[0] = 1;}
    // if (graphHours[0] == null) {graphHours[0] = 6;}
    // if (graphDays[1] == null) {graphDays[1] = 1;}
    // if (graphHours[1] == null) {graphHours[1] = 6;}
    // if (graphDays[2] == null) {graphDays[2] = 1;}
    // if (graphHours[2] == null) {graphHours[2] = 6;}
    // if (graphDays[3] == null) {graphDays[3] = 1;}
    // if (graphHours[3] == null) {graphHours[3] = 6;}
    // if (graphDays[4] == null) {graphDays[4] = 1;}
    // if (graphHours[4] == null) {graphHours[4] = 6;}
    // if (graphDays[5] == null) {graphDays[5] = 1;}
    // if (graphHours[5] == null) {graphHours[5] = 6;}


    if (startupRunning == 1) {setupReconnect();}
}
    
function setupReconnect(){
    // console.log('setupReconnect');
    $.ajax({
        method: "GET",
        url: "/php/reconnectDelete.php",
        cache: false,
        dataType: "json",
        // data: {'v':command},
        success: function(dataWindow) {
            console.log("Success Deleting File");
            // console.log(dataWindow);
        },
        error: function(dataWindow) {
            // stopSendingData = 1;
            // console.log(dataWindow);
            // console.log('error  Deleting File');
        }
    });
    loadLayout();
    
    // update time on website
    printDateTime();
    // var currentTime;
    // if (window.innerWidth < 750) {
    //     if (timeFormat == 0) {currentTime = moment().format('MM/DD/YY, HH:mm:ss');}
    //     else if (timeFormat == 1) {currentTime = moment().format('MM/DD/YY, h:mm:ss a');}
    // }
    // else {
    //     if (timeFormat == 0) {currentTime = moment().format('dddd - MMMM Do YYYY, HH:mm:ss');}
    //     else if (timeFormat == 1) {currentTime = moment().format('dddd - MMMM Do YYYY, h:mm:ss a');}
    // }
    // document.getElementById("headerDatetime").innerHTML = currentTime;
    // printAcOutletsWidget();
    // printAcOutlets();  // load AC outlet widget when it opens
    // printDcPorts();  // load DC port widget when it opens
    // printDcPortsWidget();  // load DC port widget when it opens
    // printLightWidget();
    // printCustomRulesWidget();
    // printDosingPumpsWidget();
    // printSensors();
    // printFlowMeters();

    setTimeout(function(){
        console.log("LOGGED OUT");
        window.location.href = "/index.php";
        $.ajax({  // update database with ds18b20 sensor ids
            method: "POST",
            url: "/logout.php",
            dataType: "text/plain"
        });
    }, 86400000);

    setInterval(printGraphs, 300000);

    // $('.widgetProbesChartRefreshButton').click(function() { printProbeGraphs(); })
    // printProbeGraphs();
    update_ds18b20();
    updateProbes();
    checkI2C();

    checkIfUpdateRan();

    // these loop over while web page is open
    setInterval(update_ds18b20, 1000);
    setInterval(autoUpdateOutletIcons, 100);
    setInterval(autoUpdateDcIcons, 100);
    // setInterval(update_ds18b20, 1000);
    setInterval(updateProbes, 1000);
    setInterval(checkI2C, 10000);

    setInterval(updateNextLightDashboard, 1000);

    
    (function loop2()  // using to send dosing pump status to update UI, need to replace with web socket sending command to frontend without request
    {  // using to send dosing pump status to update UI, need to replace with web socket sending command to frontend without request
        if (updateAvailable != 2) {
            if (stopSendingData == 100) {}  // pause communications for LED sliders
            else if (stopSendingData == 0) {  // ask for data if needed
                stopSendingData = 0;  // don't ask for data again until data has been returned
                var command = "997";
                // if (displayScreen == 0) {sendToBackend(command);}
                sendDoseRequestToBackend(command);
            }
        }
        setTimeout(loop2, 100);
    })();

    (function loop()  // using this instead of setInterval so we can change how often it loops
    {
        //   setInterval(function() {
        // console.log('running');
            // console.log('stopSendingData = ' + stopSendingData);
        //     console.log('updateAvailable = ' + updateAvailable);
        if (updateAvailable != 2) {
            if (stopSendingData == 100) {}  // pause communications for LED sliders
            else if (stopSendingData == 0) {  // ask for data if needed
                stopSendingData = 1;  // don't ask for data again until data has been returned
                var command = "998";
                // if (displayScreen == 0) {sendToBackend(command);}
                sendToBackend(command);
            }
            else if (stopSendingData <= 5) {stopSendingData++;}  // allow up to 5 seconds without a connection
        }
        

        if (stopSendingData > 5) {  // check if txt file exists so we know backend is running
            console.log('reconnecting');
            if (stopSendingData != 100) {document.getElementById("connectedIcon").src = "images/icons/disconn.png";}
            sendingDataSpeed = 1000;

            $.ajax({
                type: "POST",
                url: "/reconnected.txt",  // file created by backend when c++ program starts
                // data: dataString,
                success: function(data){  // file is found, we can delete txt file and startup communications 
                    // console.log(data);
                    stopSendingData = 0;
                    sendingDataSpeed = 1000;
                    if (displayScreen == 8) {closeDs18b20Popup(); loadLayout();}
                    else if (displayScreen == 1) {closeDs18b20Popup();}
                    $.ajax({
                        method: "POST",
                        url: "/php/reconnectDelete.php",
                        cache: false,
                        dataType: "json",
                        // data: {'v':command},
                        success: function(dataWindow) {
                            // console.log("Success Deleting File");
                            // console.log(dataWindow);
                        },
                        error: function(dataWindow) {
                            // stopSendingData = 1;
                            // console.log(dataWindow);
                            // console.log('error  Deleting File');
                        }
                    });
                },
                error: function(data) {
                    // console.log(data);
                    if (displayScreen == 8) {closeDs18b20Popup(); loadLayout();}
                    else if (displayScreen == 1) {closeDs18b20Popup();}
                    // console.log('error - searching for file');
                }
            
            });
        }
    // }, sendingDataSpeed);
    
        setTimeout(loop, sendingDataSpeed);
    })();
    startupRunning = 0;
    console.log('startup finished');
}