var i2cDeviceTypeIDSaved = [];
var i2cDecAddressSaved = [];
var i2cEnabledSaved = [];
var i2cNewSaved = [];
var i2cTotalSaved = 0;
var i2cTotalNew = 0;
var i2cDevAddressNew = [];
var configuringI2C = 0;  // flag so we know new I2C device has been detected
var newI2CAddress = 0;  // track new I2C address until saved
var newI2Cname = "";  // track custom name for new I2C device until saved
var i2cDeviceTypeID = 0;  // track what new I2C type is being added
var i2cNewEnableCh = [];  // track which pins are enabled when configuing new PCA9685 until saved
var pca9685NewPinIcon = [];  // track icon for pins when configuring new PCA9685 until saved
var newDriverID = 0;

function checkI2C() {  // Check every 10 seconds if new I2C devices have been detected
    // console.log('checkI2C&&&&&&&&&&&&&&&&&&&&&&&&&&');

    $.ajax({  // get i2c devices connected
        url: "/php/i2cRead.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) 
        {
            // console.log('checkI2C .........................................');
            // console.log(dataWindow);
            // empty variables
            i2cDeviceTypeIDSaved = [];
            i2cDecAddressSaved = [];
            i2cEnabledSaved = [];
            i2cNewSaved = [];
            i2cDevAddressNew = [];
            i2cTotalSaved = 0;
            i2cTotalNew = 0;

            for(var i in dataWindow) 
            {
                i2cDeviceTypeIDSaved.push(dataWindow[i].i2cDeviceTypeID);  // device type
                i2cDecAddressSaved.push(dataWindow[i].decAddress);  // decimal i2c address
                i2cEnabledSaved.push(dataWindow[i].enabled);  // track if device is enabled
                i2cNewSaved.push(dataWindow[i].new);  // track if device is new or already setup
                if (i2cNewSaved[i] == 1) {i2cDevAddressNew[i2cTotalNew] = i2cDecAddressSaved[i]; i2cTotalNew++;}  // count number of new devices found and store addresses so they can be configured
                i2cTotalSaved++;  // track how many i2c devices are in the database
            }

            if ((i2cTotalNew > 0) && (configuringI2C == 0)) {configureNewI2C();}  // open popup if new devices are found
            if ((i2cTotalNew == 0) && (startupWizardRunning == 1)) {startupScanOneWire();}  // run oneWire bus scan if startup wizard is running and there are no new i2c devices to configure
            
            // console.log("i2cTotalSaved        = " + i2cTotalSaved);
            // console.log("i2cTotalNew          = " + i2cTotalNew);
            // console.log("i2cDeviceTypeIDSaved = " + i2cDeviceTypeIDSaved);
            // console.log("i2cDecAddressSaved   = " + i2cDecAddressSaved);
            // console.log("i2cEnabledSaved      = " + i2cEnabledSaved);
            // console.log("i2cNewSaved          = " + i2cNewSaved);
            // console.log("i2cDevAddressNew     = " + i2cDevAddressNew);
            // console.log('');
        },
        error: function(dataWindow) {
            // console.log('ERROR - checkI2C() ---');
            // console.log(dataWindow);// no sensor data
        }
    });
}

function configureNewI2C() {  // load popup box to select which I2C device type was detected
    // console.log('configureNewI2C ------------');
    configuringI2C = 1;  // set flag so system knows i2c device is being configured
    newI2CAddress = i2cDevAddressNew[0];  // temporarily store i2c address to use at later point in setup

    var i2cGuess = "";
    if (newI2CAddress == 99) {i2cGuess = "(This is likely a pH circuit!)";}

    $('.ds18b20Popup-body').empty();
    ds18b20Popup.style.display = "block";
    $('#popupBackground').show();  // grey out background
    document.querySelector("body").style.overflow = 'hidden';

    $('.ds18b20PopupHeader').empty();
    $(".ds18b20PopupHeader").append("New I2C Device");
    
    $(".ds18b20Popup-body").append(
        '<p></p>\
        <p style="text-align: center;">Robo-Tank has detected a new I2C device which needs to be configured.</p>\
        <p style="text-align: center;">The new I2C address is<span class="newAdd"> ' + newI2CAddress + '</span>' + ' ' + i2cGuess + '</p>\
        <p class="i2cNew">Click the picture of what you just added.</p>\
        <div class="container">\
            <div class="row">\
                <div class="col-lg-6 i2cCategory" onclick="newPhName()"><p class="i2cNew">pH Circuit</p><p><img width="100%" src="images/wizard/ph.jpg" alt="Robo-Tank pH Circuit"></p></div>\
                <div class="col-lg-6 i2cCategory" onclick="newPCA9685name()"><p class="i2cNew">PCA9685 Driver</p><img width="100%" src="images/wizard/pca9685.jpg" alt="Robo-Tank PCA9685 Expander"></div>\
            </div>\
        </div><p>&nbsp;</p>');
}

function newPhName() {  // add custom name for new pH circuit
    i2cDeviceTypeID = 1;

    $('.ds18b20PopupHeader').empty();
    $(".ds18b20PopupHeader").append("Adding New pH Circuit");
    
    $('.ds18b20Popup-body').empty();
    $(".ds18b20Popup-body").append(
        '<p>&nbsp;</p>\
        <p style="text-align: center;">Let\'s customize your pH probe.</p>\
        <p class="i2cNew">Give your probe a name.</p>\
        <div class="container">\
            <form class="row">\
                <label class="col-lg-3 i2cName" for="probeName">pH Probe Custom Name:</label>\
                <input class="col-lg-9 i2cNameField" type="text" id="probeName" name="probeName"><br>\
            </form>\
        </div>\
        <div id="popupErrorMessage"></div><br>\
        <div class="widgetButtonBox">\
            <button class="button _wide" type="button" onclick="configureNewI2C()">Back</button>\
            <button class="button _wide" type="button" onclick="saveNewPh()">Save</button>\
        </div></br>');
        // <center><input class="button" type="button" value="Back" onclick="configureNewI2C()" />\
        // <input class="button" type="button" value="Save" onclick="saveNewPh()" /></center><br>');
}

function newPCA9685name() {  // add custom name for new pca9685
    i2cDeviceTypeID = 2;
    
    $('.ds18b20PopupHeader').empty();
    $(".ds18b20PopupHeader").append("Adding New PCA9685 Driver");
    ds18b20Popup.style.marginTop = "0px";

    $('.ds18b20Popup-body').empty();
    $(".ds18b20Popup-body").append(
        '<p>&nbsp;</p>\
        <p style="text-align: center;">Let\'s setup your new PCA9685 driver.</p>\
        <p class="i2cNew">Give your driver a name.</p>\
        <div class="container">\
            <form class="row">\
                <label class="col-lg-3 i2cName" for="pca9685Name">PCA9685 Custom Name:</label>\
                <input class="col-lg-9 i2cNameField" type="text" id="pca9685Name" name="pca9685Name" value=' + newI2Cname + '><br>\
            </form>\
        </div>\
        <div id="popupErrorMessage"></div><br>\
        <div class="widgetButtonBox">\
            <button class="button _wide" type="button" onclick="configureNewI2C()">Back</button>\
            <button class="button _wide" type="button" onclick="assignPCA9685pins()">Next</button>\
        </div></br>');
        // <center><input class="button" type="button" value="Back" onclick="configureNewI2C()" />\
        // <input class="button" type="button" value="Next" onclick="assignPCA9685pins()" /></center><br>');
}

function newPCA9685enableCh(ch) {  // enable/disable pca9685 pin
    if (i2cNewEnableCh[ch] == 1) {
        i2cNewEnableCh[ch] = 0;
        $('.enable_' + ch).css({"background-color":"#e6e6e6"});
        document.getElementById('pca9685PinName_' + ch).style.backgroundColor = "#e6e6e6";  // 
        document.getElementById('pca9685PinName_' + ch).disabled = true;
        document.getElementById('function_' + ch).disabled = true;
        document.getElementById('function_' + ch).style.backgroundColor = "#e6e6e6";  // 
    }
    else {
        i2cNewEnableCh[ch] = 1;
        $('.enable_' + ch).css({"background-color":"#fffc9e"});
        document.getElementById('pca9685PinName_' + ch).style.backgroundColor = "#fffc9e";  // 
        document.getElementById('pca9685PinName_' + ch).disabled = false;
        document.getElementById('function_' + ch).disabled = false;
        document.getElementById('function_' + ch).style.backgroundColor = "#fffc9e";  // 
    }
    // for (var i = 0; i < 16; i++) { // 
    //     console.log(i2cNewEnableCh[i]);
    // }
}

function assignPCA9685pins() {  // assign pca9685 pins
    newI2Cname = document.getElementById("pca9685Name").value;  // get custom name entered in form
    // console.log('assignPCA9685pins PRESSED --------------------------------');
    // console.log('newI2Cname      = ' + newI2Cname);
    // console.log('newI2CAddres    = ' + newI2CAddress);
    if (newI2Cname == "")  // check if custom name was entered, if not warn user.
    {
        document.getElementById('popupErrorMessage').innerHTML = "Please enter a custom name to continue!";
    }
    else  // all good so load pin assignment table
    {
        ds18b20Popup.style.marginTop = "-100px";  // shift popup on screen

        $('.ds18b20Popup-body').empty();
        $(".ds18b20Popup-body").append(
            '</br>\
            <p style="text-align: center; font-weight: bold; font-size: 15px;">Right on! You have 16 new outputs to work with.</p>\
            <p>Assign pins that you\'ll be using a custom name and the function. If you won\'t be using the pin leave it blank.\
            <div class="newPCA9685diagram"><img width="100%" src="images/wizard/pca9685_expander.jpg" alt="Robo-Tank PCA9685 Expander"></div>\
            <div class="tg-wrap">\
            <table id="tg-qrorO" class="tg">\
                <thead>\
                <tr>\
                    <th class="tg-km22" colspan="5">Assign PCA9685 Pins</th>\
                </tr>\
                </thead>\
                <tbody>\
                <tr>\
                    <td class="tg-6e8n">Pin #</td>\
                    <td class="tg-6e8n">Function</td>\
                    <td class="tg-6e8n">Custom Name</td>\
                    <td class="tg-6e8n">Icon</td>\
                    <td class="tg-6e8n">Enable</td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_0">0</td>\
                    <td class="tg-0pky enable_0">\
                        <select class="tg-name" id="function_0" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_0"><input class="tg-name" type="text" disabled id="pca9685PinName_0"></td>\
                    <td class="tg-0pky enable_0" id="icon_0"><img class="newPCA9685icon" onclick="newPCA9685icon(0)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_0"><input class="tg-enable" type="checkbox" id="enable_0" onclick="newPCA9685enableCh(0)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_1">1</td>\
                    <td class="tg-0pky enable_1">\
                        <select class="tg-name" id="function_1" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_1"><input class="tg-name" type="text" disabled id="pca9685PinName_1"></td>\
                    <td class="tg-0pky enable_1" id="icon_1"><img class="newPCA9685icon" onclick="newPCA9685icon(1)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_1"><input class="tg-enable" type="checkbox" id="enable_1" onclick="newPCA9685enableCh(1)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_2">2</td>\
                    <td class="tg-0pky enable_2">\
                        <select class="tg-name" id="function_2" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_2"><input class="tg-name" type="text" disabled id="pca9685PinName_2"></td>\
                    <td class="tg-0pky enable_2" id="icon_2"><img class="newPCA9685icon" onclick="newPCA9685icon(2)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_2"><input class="tg-enable" type="checkbox" id="enable_2" onclick="newPCA9685enableCh(2)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_3">3</td>\
                    <td class="tg-0pky enable_3">\
                        <select class="tg-name" id="function_3" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_3"><input class="tg-name" type="text" disabled id="pca9685PinName_3"></td>\
                    <td class="tg-0pky enable_3" id="icon_3"><img class="newPCA9685icon" onclick="newPCA9685icon(3)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_3"><input class="tg-enable" type="checkbox" id="enable_3" onclick="newPCA9685enableCh(3)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_4">4</td>\
                    <td class="tg-0pky enable_4">\
                        <select class="tg-name" id="function_4" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_4"><input class="tg-name" type="text" disabled id="pca9685PinName_4"></td>\
                    <td class="tg-0pky enable_4" id="icon_4"><img class="newPCA9685icon" onclick="newPCA9685icon(4)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_4"><input class="tg-enable" type="checkbox" id="enable_4" onclick="newPCA9685enableCh(4)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_5">5</td>\
                    <td class="tg-0pky enable_5">\
                        <select class="tg-name" id="function_5" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_5"><input class="tg-name" type="text" disabled id="pca9685PinName_5"></td>\
                    <td class="tg-0pky enable_5" id="icon_5"><img class="newPCA9685icon" onclick="newPCA9685icon(5)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_5"><input class="tg-enable" type="checkbox" id="enable_5" onclick="newPCA9685enableCh(5)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_6">6</td>\
                    <td class="tg-0pky enable_6">\
                        <select class="tg-name" id="function_6" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_6"><input class="tg-name" type="text" disabled id="pca9685PinName_6"></td>\
                    <td class="tg-0pky enable_6" id="icon_6"><img class="newPCA9685icon" onclick="newPCA9685icon(6)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_6"><input class="tg-enable" type="checkbox" id="enable_6" onclick="newPCA9685enableCh(6)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_7">7</td>\
                    <td class="tg-0pky enable_7">\
                        <select class="tg-name" id="function_7" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_7"><input class="tg-name" type="text" disabled id="pca9685PinName_7"></td>\
                    <td class="tg-0pky enable_7" id="icon_7"><img class="newPCA9685icon" onclick="newPCA9685icon(7)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_7"><input class="tg-enable" type="checkbox" id="enable_7" onclick="newPCA9685enableCh(7)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_8">8</td>\
                    <td class="tg-0pky enable_8">\
                        <select class="tg-name" id="function_8" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_8"><input class="tg-name" type="text" disabled id="pca9685PinName_8"></td>\
                    <td class="tg-0pky enable_8" id="icon_8"><img class="newPCA9685icon" onclick="newPCA9685icon(8)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_8"><input class="tg-enable" type="checkbox" id="enable_8" onclick="newPCA9685enableCh(8)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_9">9</td>\
                    <td class="tg-0pky enable_9">\
                        <select class="tg-name" id="function_9" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_9"><input class="tg-name" type="text" disabled id="pca9685PinName_9"></td>\
                    <td class="tg-0pky enable_9" id="icon_9"><img class="newPCA9685icon" onclick="newPCA9685icon(9)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_9"><input class="tg-enable" type="checkbox" id="enable_9" onclick="newPCA9685enableCh(9)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_10">10</td>\
                    <td class="tg-0pky enable_10">\
                        <select class="tg-name" id="function_10" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_10"><input class="tg-name" type="text" disabled id="pca9685PinName_10"></td>\
                    <td class="tg-0pky enable_10" id="icon_10"><img class="newPCA9685icon" onclick="newPCA9685icon(10)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_10"><input class="tg-enable" type="checkbox" id="enable_10" onclick="newPCA9685enableCh(10)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_11">11</td>\
                    <td class="tg-0pky enable_11">\
                        <select class="tg-name" id="function_11" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_11"><input class="tg-name" type="text" disabled id="pca9685PinName_11"></td>\
                    <td class="tg-0pky enable_11" id="icon_11"><img class="newPCA9685icon" onclick="newPCA9685icon(11)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_11"><input class="tg-enable" type="checkbox" id="enable_11" onclick="newPCA9685enableCh(11)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_12">12</td>\
                    <td class="tg-0pky enable_12">\
                        <select class="tg-name" id="function_12" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_12"><input class="tg-name" type="text" disabled id="pca9685PinName_12"></td>\
                    <td class="tg-0pky enable_12" id="icon_12"><img class="newPCA9685icon" onclick="newPCA9685icon(12)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_12"><input class="tg-enable" type="checkbox" id="enable_12" onclick="newPCA9685enableCh(12)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_13">13</td>\
                    <td class="tg-0pky enable_13">\
                        <select class="tg-name" id="function_13" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_13"><input class="tg-name" type="text" disabled id="pca9685PinName_13"></td>\
                    <td class="tg-0pky enable_13" id="icon_13"><img class="newPCA9685icon" onclick="newPCA9685icon(13)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_13"><input class="tg-enable" type="checkbox" id="enable_13" onclick="newPCA9685enableCh(13)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_14">14</td>\
                    <td class="tg-0pky enable_14">\
                        <select class="tg-name" id="function_14" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_14"><input class="tg-name" type="text" disabled id="pca9685PinName_14"></td>\
                    <td class="tg-0pky enable_14" id="icon_14"><img class="newPCA9685icon" onclick="newPCA9685icon(14)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_14"><input class="tg-enable" type="checkbox" id="enable_14" onclick="newPCA9685enableCh(14)"></td>\
                </tr>\
                <tr>\
                    <td class="tg-0pky enable_15">15</td>\
                    <td class="tg-0pky enable_15">\
                        <select class="tg-name" id="function_15" disabled>\
                            <option value="0"></option>\
                            <option value="1">AC Outlet</option>\
                            <option value="2">DC Port</option>\
                            <option value="11">Light</option>\
                            <option value="12">Dosing Pump</option>\
                        </select>\
                    </td>\
                    <td class="tg-z0iz enable_15"><input class="tg-name" type="text" disabled id="pca9685PinName_15"></td>\
                    <td class="tg-0pky enable_15" id="icon_15"><img class="newPCA9685icon" onclick="newPCA9685icon(15)" src="images/icons/add.png" alt="Assign Icon"></td>\
                    <td class="tg-0pky enable_15"><input class="tg-enable" type="checkbox" id="enable_15" onclick="newPCA9685enableCh(15)"></td>\
                </tr>\
                </tbody>\
            </table>\
            </div>\
            <p>&nbsp;</p>\
            <center>\
            <div id="newPCA9685error"></div><br>\
            <div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="saveNewPCA9685()">Save</button>\
            </div></br>');
        //     <input class="button" type="button" value="Save" onclick="saveNewPCA9685()" /></center><br>');
    }
    // var TGSort=window.TGSort||function(n){"use strict";function r(n){return n?n.length:0}function t(n,t,e,o=0){for(e=r(n);o<e;++o)t(n[o],o)}function e(n){return n.split("").reverse().join("")}function o(n){var e=n[0];return t(n,function(n){for(;!n.startsWith(e);)e=e.substring(0,r(e)-1)}),r(e)}function u(n,r,e=[]){return t(n,function(n){r(n)&&e.push(n)}),e}var a=parseFloat;function i(n,r){return function(t){var e="";return t.replace(n,function(n,t,o){return e=t.replace(r,"")+"."+(o||"").substring(1)}),a(e)}}var s=i(/^(?:\s*)([+-]?(?:\d+)(?:,\d{3})*)(\.\d*)?$/g,/,/g),c=i(/^(?:\s*)([+-]?(?:\d+)(?:\.\d{3})*)(,\d*)?$/g,/\./g);function f(n){var t=a(n);return!isNaN(t)&&r(""+t)+1>=r(n)?t:NaN}function d(n){var e=[],o=n;return t([f,s,c],function(u){var a=[],i=[];t(n,function(n,r){r=u(n),a.push(r),r||i.push(n)}),r(i)<r(o)&&(o=i,e=a)}),r(u(o,function(n){return n==o[0]}))==r(o)?e:[]}function v(n){if("TABLE"==n.nodeName){for(var a=function(r){var e,o,u=[],a=[];return function n(r,e){e(r),t(r.childNodes,function(r){n(r,e)})}(n,function(n){"TR"==(o=n.nodeName)?(e=[],u.push(e),a.push(n)):"TD"!=o&&"TH"!=o||e.push(n)}),[u,a]}(),i=a[0],s=a[1],c=r(i),f=c>1&&r(i[0])<r(i[1])?1:0,v=f+1,p=i[f],h=r(p),l=[],g=[],N=[],m=v;m<c;++m){for(var T=0;T<h;++T){r(g)<h&&g.push([]);var C=i[m][T],L=C.textContent||C.innerText||"";g[T].push(L.trim())}N.push(m-v)}t(p,function(n,t){l[t]=0;var a=n.classList;a.add("tg-sort-header"),n.addEventListener("click",function(){var n=l[t];!function(){for(var n=0;n<h;++n){var r=p[n].classList;r.remove("tg-sort-asc"),r.remove("tg-sort-desc"),l[n]=0}}(),(n=1==n?-1:+!n)&&a.add(n>0?"tg-sort-asc":"tg-sort-desc"),l[t]=n;var i,f=g[t],m=function(r,t){return n*f[r].localeCompare(f[t])||n*(r-t)},T=function(n){var t=d(n);if(!r(t)){var u=o(n),a=o(n.map(e));t=d(n.map(function(n){return n.substring(u,r(n)-a)}))}return t}(f);(r(T)||r(T=r(u(i=f.map(Date.parse),isNaN))?[]:i))&&(m=function(r,t){var e=T[r],o=T[t],u=isNaN(e),a=isNaN(o);return u&&a?0:u?-n:a?n:e>o?n:e<o?-n:n*(r-t)});var C,L=N.slice();L.sort(m);for(var E=v;E<c;++E)(C=s[E].parentNode).removeChild(s[E]);for(E=v;E<c;++E)C.appendChild(s[v+L[E-v]])})})}}n.addEventListener("DOMContentLoaded",function(){for(var t=n.getElementsByClassName("tg"),e=0;e<r(t);++e)try{v(t[e])}catch(n){}})}(document)

    for (var i = 0; i < 16; i++) { // 
        if (typeof i2cNewEnableCh[i] == 'undefined') i2cNewEnableCh[i] = 0;  // set enabled to no if undefined
        // console.log(i2cNewEnableCh[i]);
    }
}

function newPCA9685icon(ch) {  // load icons in popup box
    if(i2cNewEnableCh[ch] == 1) {
        // console.log('newPCA9685icon-----------');
        $('#editPopup').show();  // open popup
        $('#editPopup').draggable();
        // clearSettingsPopup();
        $('.editBoxHeader').empty();
        $('.editPopupBox').empty();
        $('.editPopupBox2').empty();
        $('.editPopupInstructions').empty();
        $('.editPopupButtons').empty();
        
        $('.editBoxHeader').append("Available Icons");

        $('.editPopupButtons').append(
            '<div class="widgetButtonBox">\
                <button class="button _wide cancel" type="button">Cancel</button>\
            </div></br>');
            // <button class="button cancel">Cancel</button>');  // add cancel button

        $('.editPopupInstructions').append("Select an icon to continue!");

        $('.editPopupBox').append("<div class='loadAllIconsBox'>");
        for (i = 1; i <= 60; i++) {  // load all icons to screen
            $('.editPopupBox').append(
                "<img onclick='savePCA9685icon(this.id," + ch + ")' class='updatePortIcons' id='" + i + "' src='images/Outlets/OutLD" + i + "M.png'>");
                // "<div class='loadAllIcons' id='" + i + "' onClick='savePCA9685icon(this.id," + ch + ")'><img width='60px' src='images/Outlets/OutLD" + i + "L.png'></div>");
            // document.getElementById('editPopupBox2').innerHTML += `<img src='images/Outlets/OutLD` + i + `L.png'>`;
        }
        $('.editPopupBox').append("</div>");
        
        $('.cancel').click(function() { $('#editPopup').hide(); })  // hide popup
    }
}

function savePCA9685icon(ID,ch) {  // save icon for pin
    // console.log('savePCA9685icon--------- ' + ID + " - " + ch);
    $('#editPopup').hide();  // hide icon popup
    pca9685NewPinIcon[ch] = ID;  // store iconID to save
    document.getElementById('icon_' + ch).innerHTML = '<img height="auto" class="editPCA9685icon" onclick="newPCA9685icon(' + ch + ')" src="images/Outlets/OutLD' + ID + 'L.png" alt="Assign Icon">';
}

function saveNewPCA9685() {  // save pin assignments to database
    // console.log(' ');
    console.log('saveNewPCA9685 PRESSED --------------------------------');
    console.log(newI2Cname);
    console.log(newI2CAddress);
    console.log(newDriverID);
    var pinName = [];  // 
    var pinFunction = [];  //
    // var error = 0;
    
    for (var i = 0; i < 16; i++) {  // go through all pins in table to compile data
        if (i2cNewEnableCh[i] == false) {pinFunction[i] = 100;}  // mark pinTypeID unassigned if not being used
        else {pinFunction[i] = document.getElementById("function_" + i).value;}  // get pinTypeID selected if enabled

        pinName[i] = document.getElementById("pca9685PinName_" + i).value;  // get custom name for pin

        if ((pinFunction[i] == 0) && (i2cNewEnableCh[i] == true)) {  // check that pin has a function assigned if enabled
            document.getElementById('function_' + i).focus();  // set focus to field that needs data
            document.getElementById('newPCA9685error').innerHTML = "Select a function for pin # " + i + " or disable the pin.";  // popup warning
            // error = 1;
            return;
        }

        if ((pinName[i] == "") && (i2cNewEnableCh[i] == true)) {  // check tha tpin has a custom name assigned if enabled
            document.getElementById('pca9685PinName_' + i).focus();  // set focus to field that needs data
            document.getElementById('newPCA9685error').innerHTML = "Enter a name for pin # " + i + " or disable the pin.";  // popup warning
            // error = 1;
            return;
        }

        if ((typeof pca9685NewPinIcon[i] == 'undefined') && (i2cNewEnableCh[i] == true)) {  // check tha tpin has a custom name assigned if enabled
            document.getElementById('icon_' + i).focus();  // set focus to field that needs data
            document.getElementById('newPCA9685error').innerHTML = "Select an icon for pin # " + i + " or disable the pin.";  // popup warning
            // error = 1;
            return;
        }

        console.log(pinName[i] + " - " + pinFunction[i] + " - " + pca9685NewPinIcon[i] + " - " + i2cNewEnableCh[i]);
    }
    // if (error == 1) return;  // if there was an error don't proceed 

    document.querySelector("body").style.overflow = 'visible';
    
    console.log('saveNewDriver------ ' + i2cDeviceTypeID);
    console.log('newI2Cname   ------ ' + newI2Cname);
    $.ajax({  // save new driver to database
        url: "/php/driverSaveNew.php",
        method: "POST",
        cache: false,
        data: {
                "id": '1',
                "n": newI2Cname
        },
        success: function(dataWindow)  // on success save 16 pins for pca9685
        {
            // console.log('saveNewDriver COMPLETE......');
            newDriverID = (dataWindow[0].driverID);  // get driverID just added so it can be saved with pins
            console.log('newI2CAddress ------ ' + newI2CAddress);
            console.log('newDriverID   ------ ' + newDriverID);
    
            $.ajax({  // assign new driverID to pca9685 device
                method: "POST",
                url: "/php/i2cUpdateDriverID.php",
                dataType: "text/plain",
                cache: false,
                data: {
                        "a": newI2CAddress,
                        "d": newDriverID
                }
            });

            for (var i = 0; i < 16; i++) {  // save all pins to database
                console.log('saving------ ');
                if (typeof pca9685NewPinIcon[i] == 'undefined') {pca9685NewPinIcon[i] = 0;}  // if no pin icon set to 0
                $.ajax({  // save pins
                    method: "POST",
                    url: "/php/driverSaveNewPins.php",
                    dataType: "text/plain",
                    cache: false,
                    data: {
                            "d": newDriverID,
                            "a": i2cNewEnableCh[i],
                            "t": pinFunction[i],
                            "n": pinName[i],
                            "i": pca9685NewPinIcon[i],
                            "g": i
                    }
                });
            }
            updateNewI2Cdevice();  // mark i2c device as setup complete
            

            // var i = 0;
            // // myLoop(i);
            // (function myLoop(j) {
            //     setTimeout(function() {
            //         // console.log('hello'); //  your code here
            //         console.log('saving------ ' + i);
            //         if (typeof pca9685NewPinIcon[i] == 'undefined') {pca9685NewPinIcon[i] = 0;}  // if no pin icon set to 0
            //         $.ajax({  // save pins
            //             method: "POST",
            //             url: "/php/driverSaveNewPins.php",
            //             dataType: "text/plain",
            //             cache: false,
            //             data: {
            //                     "d": newDriverID,
            //                     "a": i2cNewEnableCh[i],
            //                     "t": pinFunction[i],
            //                     "n": pinName[i],
            //                     "i": pca9685NewPinIcon[i],
            //                     "g": i
            //             }
            //         });
            //         // console.log('saving------ ' + j);
                    
            //         // if (i < 15) {i--; myLoop(i);}
            //         if (--j >= 0) {i++; myLoop(j);}   //  decrement i and call myLoop again if i > 0
            //         if (j == 0) {
            //             updateNewI2Cdevice();  // mark i2c device as setup complete
            //             console.log('saving finsihed ------ ' + i);
            //             i2cTotalNew--;  // remove one from count and check if another needs to be added
            //             if (i2cTotalNew > 0) {setTimeout(checkI2C, 500);}  // wait 500ms to check if another detected device is waiting
            //             else {configuringI2C = 0;}  // finished configuring
                    
            //             if ((i2cTotalNew == 0) && (startupWizardRunning == 1)) {startupScanOneWire();}  // scan one wire bus if initial setup is running
            //             else {ds18b20Popup.style.display = "none";}  // hide popup
            //             $('#popupBackground').hide();  // hide greyed out background
            //             setTimeout(saveNewPCA9685Finish, 1000);  // tell backend setup is complete
            //         }
            //     }, 300)
            // })(15);                   //  pass the number of iterations as an argument
        },
        error: function(dataWindow) {
            console.log('ERROR - saveNewPCA9685() ---');
            console.log(dataWindow);// no sensor data
        }
    });
    
    i2cTotalNew--;  // remove one from count and check if another needs to be added
    if (i2cTotalNew > 0) {setTimeout(checkI2C, 500);}  // wait 500ms to check if another detected device is waiting
    else {configuringI2C = 0;}  // finished configuring

    if ((i2cTotalNew == 0) && (startupWizardRunning == 1)) {startupScanOneWire();}  // scan one wire bus if initial setup is running
    else {ds18b20Popup.style.display = "none";}  // hide popup
    $('#popupBackground').hide();  // hide greyed out background
    setTimeout(saveNewPCA9685Finish, 1000);  // tell backend setup is complete
}

function saveNewPCA9685Finish() {  // tell backend to check for updated driver / i2c information
    var command = "40";
    sendToBackend(command);
    // updateProbes();
    // console.log('saveNewPCA9685Finish------ ' + command);
}

function saveNewPh() {  // save custom name to database
    newI2Cname = document.getElementById("probeName").value;  // get custom name entered in form
    // console.log('saveNewPh PRESSED --------------------------------');
    // console.log(newI2Cname);
    // console.log(newI2CAddress);
    if (newI2Cname == "")  // check if custom name was entered, if not warn user.
    {
        document.getElementById('popupErrorMessage').innerHTML = "Please enter a custom name to continue!";
    }
    else  // all good save and close popup
    {
        updateNewI2Cdevice();  // mark i2c device as setup complete
        $.ajax({  // save new probe to database
            method: "POST",
            url: "/php/probeSaveNew.php",
            cache: false,
            data: {
                    "a": newI2CAddress,
                    "n": newI2Cname
            },
            success: function(dataWindow) {
                // console.log("Success Deleting File");
                // console.log(dataWindow);
                configuringI2C = 0;  // mark name check complete so we can redraw widget on dashboard
                i2cTotalNew--;  // remove one from count and check if another needs to be added
                if (i2cTotalNew > 0) {setTimeout(checkI2C, 500);}  // wait 500ms to check if another 

                if ((i2cTotalNew == 0) && (startupWizardRunning == 1)) {startupScanOneWire();}
                else {ds18b20Popup.style.display = "none";}  // hide popup
                $('#popupBackground').hide();  // hide greyed out background
                document.querySelector("body").style.overflow = 'visible';
                updateProbes();
                setTimeout(saveNewPhFinish, 1000);
            },
            error: function(dataWindow) {
                // stopSendingData = 1;
                // console.log(dataWindow);
                // console.log('error  Deleting File');
            }
        });
        
    }
}

function saveNewPhFinish() {  // tell backend to check for updated driver / i2c information
    var command = "33";
    sendToBackend(command);  // tell backend to delete light mode
    redrawTempWidget = 1;
    redrawDashboardCol1();
    // console.log('saveNewPhFinish------ ' + command);
}

function updateNewI2Cdevice() {  // mark i2c device as setup complete
    // console.log('newI2CAddress------ ' + newI2CAddress);
    // console.log('i2cDeviceTypeID   ------ ' + i2cDeviceTypeID);
    $.ajax({  // update database with ds18b20 sensor ids
        method: "POST",
        url: "/php/i2cSaveNew.php",
        dataType: "text/plain",
        cache: false,
        data: {
                "a": newI2CAddress,
                "d": i2cDeviceTypeID
        }
    });
}