var enableButtonPressed = 0;
var dateData = [];

function supportRoboTank() {  // 
    var text = "";
    if (startupWizardRunning == 0) {
        text = `</br><p style="text-align: center;">Love Robo-Tank and want to support it further so it can continue to grow!</p>
        <p style="text-align: center;">A little extra goes a long way and allows me to update and improve Robo-Tank.</p>
        <p style="text-align: center;">Donate through Paypal or Bitcoin, one time or recurring. I appreciate your support.</p>
        <br>`;
    }
    else {
        text = `</br><p class="h2" style="text-align: center; padding-bottom: 8px;">The Robo-Tank app has been successfully installed!</p>
        <p style="text-align: center;">Love Robo-Tank and want to support it further so it can continue to grow!</p>
        <p style="text-align: center;">A little extra support goes a long way and allows me to update and improve Robo-Tank.</p>
        <p style="text-align: center;">If you already own the Robo-Tank controller this is not required in any way.</p>
        <br>`;
    }
    $('#popupBackground').show();  // grey out background
    $('.ds18b20Popup-body').empty();
    ds18b20Popup.style.display = "block";
    document.querySelector("body").style.overflow = 'hidden';
    $('.ds18b20PopupHeader').empty();
    $(".ds18b20PopupHeader").append("Support Robo-Tank");

    $('.ds18b20Popup-body').empty();
    $(".ds18b20Popup-body").append(
        text + `<div class="container subColumnBox">\
            <div class="row ">\
                <form class="col-sm-4 subColumn" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">\
                    <h3>Monthly Support</h3>\
                    <img style="padding-bottom: 15px;" src="images/icons/paypal.png" alt="PayPal">\
                    <input type="hidden" name="cmd" value="_s-xclick">\
                    <input type="hidden" name="hosted_button_id" value="BEKHYNEGACEZJ">\
                    <table>\
                        <br><b>Select Monthly Amount</b><br>\
                        <select style="margin-bottom: 20px; margin-top: 3px; width: 130px;" name="os0">\
                            <option value="Level 1">$3.00 USD</option>\
                            <option value="Level 2">$5.00 USD</option>\
                            <option value="Level 3">$10.00 USD</option>\
                            <option value="Level 4">$15.00 USD</option>\
                            <option value="Level 5">$20.00 USD</option>\
                            <option value="Level 6">$25.00 USD</option>\
                            <option value="Level 7">$30.00 USD</option>\
                            <option value="Level 8">$40.00 USD</option>\
                            <option value="Level 9">$50.00 USD</option>\
                            <option value="Level 10">$75.00 USD</option>\
                        </select>\
                    </table>\
                    <input type="hidden" name="currency_code" value="USD">\
                    <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">\
                    <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">\
                </form>\
                <form class="col-sm-4 subColumn" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">\
                    <h3>One Time Support</h3>\
                    <img style="padding-bottom: 15px;" src="images/icons/paypal.png" alt="PayPal">\
                    <input type="hidden" name="cmd" value="_s-xclick">\
                    <input type="hidden" name="hosted_button_id" value="YXYWYBG3ZCTZC">\
                    <table>\
                        <br><b>Select One Time Amount</b><br>\
                        <select style="margin-bottom: 20px; margin-top: 3px; width: 130px;" name="os0">\
                            <option value="One Time1 -">$5.00 USD</option>\
                            <option value="One Time2 -">$15.00 USD</option>\
                            <option value="One Time3 -">$25.00 USD</option>\
                            <option value="One Time4 -">$40.00 USD</option>\
                            <option value="One Time5 -">$60.00 USD</option>\
                            <option value="One Time6 -">$80.00 USD</option>\
                            <option value="One Time7 -">$100.00 USD</option>\
                            <option value="One Time8 -">$150.00 USD</option>\
                            <option value="One Time9 -">$200.00 USD</option>\
                            <option value="One Time10 -">$250.00 USD</option>\
                        </select>\
                    </table>\
                    <input type="hidden" name="currency_code" value="USD">\
                    <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">\
                    <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">\
                </form>\
                <div class="col-sm-3 subColumn">\
                    <h3>One Time Support</h3>\
                    <img style="padding: 0px 10px 19px 10px;" src="images/icons/bitcoin_logo.jpg" alt="Bitcoin">\
                    <img src="images/icons/17SFZnKsd3BDaYxokS42LCyADhX7iZpq1E.png" alt="Bitcoin">\
                </div>\
            </div>\
        </div>\
        <div style="margin-top:-15px; text-align:center; width:100%;">Contact me for other cryptocurrencies.</div>\
        <div class="widgetButtonBox">\
            <button class="button _wide" type="button" onclick="closeDs18b20Popup()">Close</button>\
        </div>\
        <p>&nbsp;</p>`);
}

function settingsSystem() {  // system settings page
    printHeaderTitle("SYSTEM SETTINGS", "settings2.png", "#ff7800");  // name and file
    removeFooter();
    displayScreen = 8;
    
    document.getElementById('content').innerHTML +=
        "<div class='cleanScreen' id='cleanScreen'>\
            <div class='settingsContainer' id='settingsContainer'></div>\
            <div class='widgetButtonBox'>\
                <button class='button _wide' style='margin-top:40px;' type='button' onclick='restartControllerConfirm()'>Restart Controller</button>\
                <button class='button _48 back_48' style='margin-top:40px;' type='button' onclick='viewSettingsMenu()'></button>\
                <button class='button _48 home_48' style='margin-top:40px;' type='button' onclick='loadLayout()'></button>\
            </div>\
            <div class='settingsContainer supportLink' id='' onclick='supportRoboTank()'>Love Robo-Tank and want to support it further?</div>\
        </div>";

    document.getElementById('settingsContainer').innerHTML +=
        '<div class="systemSettingBox">\
            <div class="systemSettingBoxLabel">Controller ID</div>\
            <div class="control-group">\
                <input class="field" style="min-width:175px; padding:3px 3px;" type="text" id="supportID" value="' + supportID + '" readOnly>\
            </div>\
            <button class="button _wide" style="width:175px; margin:80px 0px 0px 0px;" type="button" onclick="versionLog()">Version Log</button>\
        </div>\
        <div class="systemSettingBox">\
            <div class="systemSettingBoxLabel">Temperature</div>\
            <div class="control-group">\
                <label class="control control-radio">\
                    Celsius\
                    <input type="radio" name="temperature" id="celsius" onclick="updateTempCorF(0)" />\
                    <div class="control_indicator"></div>\
                </label>\
                <label class="control control-radio">\
                    Fahrenheit\
                    <input type="radio" name="temperature" id="fahrenheit" onclick="updateTempCorF(1)" />\
                    <div class="control_indicator"></div>\
                </label>\
            </div>\
        </div>\
        <div class="systemSettingBox">\
            <div class="systemSettingBoxLabel">Time Format</div>\
            <div class="control-group">\
                <label class="control control-radio">\
                    12 Hour\
                    <input type="radio" name="time" id="12hour" onclick="updateTimeFormat(1)" />\
                    <div class="control_indicator"></div>\
                </label>\
                <label class="control control-radio">\
                    24 Hour\
                    <input type="radio" name="time" id="24hour" onclick="updateTimeFormat(0)" />\
                    <div class="control_indicator"></div>\
                </label>\
            </div>\
            <button class="button _wide" style="width:175px; margin:50px 0px 0px 0px;" type="button" onclick="updateRTCdateTime()">Set Date & Time</button>\
        </div>\
        <div class="systemSettingBox" id="autoUpdateBox"></div>\
        <div class="systemVersionBox" >\
            <div class="systemSettingBoxLabel" style="text-align:center">Robo-Tank Controller</div>\
                <div class="settingsVersionText">\
                    <img id="" class="settingsVersionIcon" src="images/icons/v1.png" onclick="updateRoboTankVersionConfirm(0)" title="Robo-Tank Version 1">\
                    <label class="control control-radio" style="width:100%; text-align:center;">\
                        Version 1\
                        <input type="radio" name="version" id="version1" onclick="updateRoboTankVersionConfirm(0)" />\
                        <div class="control_indicator" style="left:63px;"></div>\
                    </label>\
                </div>\
                <div class="settingsVersionText">\
                    <img id="" class="settingsVersionIcon" src="images/icons/v2.png" onclick="updateRoboTankVersionConfirm(1)" title="Robo-Tank Version 2">\
                    <label class="control control-radio" style="width:100%; text-align:center;">\
                        Version 2\
                        <input type="radio" name="version" id="version2" onclick="updateRoboTankVersionConfirm(1)" />\
                        <div class="control_indicator" style="left:82px;"></div>\
                    </label>\
                </div>\
                <div class="settingsVersionText">\
                    <img id="" class="settingsVersionIcon" src="images/icons/v3.png" onclick="updateRoboTankVersionConfirm(2)" title="Robo-Tank Version 3">\
                    <label class="control control-radio" style="width:100%; text-align:center;">\
                        Version 3\
                        <input type="radio" name="version" id="version3" onclick="updateRoboTankVersionConfirm(2)" />\
                        <div class="control_indicator" style="left:42px;"></div>\
                    </label>\
                </div>\
        </div>';

  

    // mark tempCorF radio button active
    if (tempCorF == 0) {
        document.getElementById("celsius").checked = true;  // mark radio button checked
    }
    else if (tempCorF == 1) {
        document.getElementById("fahrenheit").checked = true;  // mark radio button checked
    }

    // mark timeFormat radio button active
    if (timeFormat == 0) {
        document.getElementById("24hour").checked = true;  // mark radio button checked
    }
    else if (timeFormat == 1) {
        document.getElementById("12hour").checked = true;  // mark radio button checked
    }
    
    // mark autoUpdate radio button active
    if (autoUpdate == 0) {
        document.getElementById("autoUpdateBox").innerHTML =  // mark radio button checked
            `<div class="systemSettingBoxLabel">Auto Update</div>\
            <div class="control-group">\
                <label class="control control-radio">\
                    On\
                        <input type="radio" name="autoUpdate" id="updateOn" class="updateOn" onclick="updateAutoUpdate(1)" />\
                    <div class="control_indicator"></div>\
                </label>\
                <label class="control control-radio">\
                    Off\
                        <input type="radio" name="autoUpdate" id="updateOff" class="updateOff" onclick="updateAutoUpdate(0)" />\
                    <div class="control_indicator"></div>\
                </label>\
                <p style="margin-top:17px"><b>Running Version </b>` + appVersion + `</p>\
            </div>\
            <button class='button _wide' id='manualUpdateButton' style='width:175px; margin:20px 0px 15px 0px;' type='button' onclick='manualUpdate()'>Check for Update</button>`;

        document.getElementById("updateOff").checked = true;  // mark radio button checked
        document.getElementById('autoUpdateBox').style.height = "195px";
    }
    else if (autoUpdate == 1) {
        document.getElementById("autoUpdateBox").innerHTML =  // mark radio button checked
            `<div class="systemSettingBoxLabel">Auto Update</div>
            <div class="control-group">
                <label class="control control-radio">
                    On
                        <input type="radio" name="autoUpdate" id="updateOn" class="updateOn" onclick="updateAutoUpdate(1)" />
                    <div class="control_indicator"></div>
                </label>
                <label class="control control-radio">
                    Off
                        <input type="radio" name="autoUpdate" id="updateOff" class="updateOff" onclick="updateAutoUpdate(0)" />
                    <div class="control_indicator"></div>
                </label>
                <p style="margin-top:17px"><b>Running Version </b>` + appVersion + `</p>
            </div>
            <button class="button _wide" style="width:175px; margin:15px 0px 0px 0px;" type="button" onclick="versionLog()">Version Log</button>`;
        document.getElementById("updateOn").checked = true;  // mark radio button checked
        document.getElementById('autoUpdateBox').style.height = "138px";
    }

    // mark controller version radio button active
    if (controllerVersion == 0) {
        document.getElementById("version1").checked = true;  // mark radio button checked
    }
    else if (controllerVersion == 1) {
        document.getElementById("version2").checked = true;  // mark radio button checked
    }
    else if (controllerVersion == 2) {
        document.getElementById("version3").checked = true;  // mark radio button checked
    }

    // updateTempCorF(tempCorF);  // load radio button on system settings page
    // updateTimeFormat(timeFormat);  // load radio button on system settings page

    // add touch commands for buttons and links
    // $('.back').click(function() { settingsMainMenu(); })
    // $('.exit').click(function() { $('#popupBackground').hide(); $('#settingsPopup').hide(); document.querySelector("body").style.overflow = 'visible';})
    // $('.celsius').click(function() { updateTempCorF(0); })
    // $('.fahrenheit').click(function() { updateTempCorF(1); })
    // $('.12hour').click(function() { updateTimeFormat(1); })
    // $('.24hour').click(function() { updateTimeFormat(0); })
}

function versionLog() {  // build version log screen
    displayScreen = 11;

    document.getElementById('content').innerHTML =
        "<div class='cleanScreen'>\
            <div class='schedulesListContainer'>\
                <div class='schedulesWidgetMenu' style='text-align:center;'>Version Log</div>\
                <div class='schedulesWidgetBoxContainer' id='schedulesWidgetBoxContainer'></div>\
            </div>\
            <div class='widgetButtonBox'>\
                <button class='button _48 back_48' style='margin-top:40px;' type='button' onclick='settingsSystem()'></button>\
            </div>\
        </div>";
        
    var divExists = document.getElementById("schedulesWidgetBoxContainer");  // check if div ID is drawn
    if(divExists){
        document.getElementById('schedulesWidgetBoxContainer').innerHTML +=  // draw schedule table header
        `<div class="schedulesList" id="schedulesListBox">
            <table class="logTable">
                <thead class="logTableHeader" id="logTableHeader">
                    <tr>
                        <th></th>
                        <th class="" id="">Version</th>
                        <th id="equipSort">Date</th>
                    </tr>
                </thead>
                <div class="logUpdating" id="logUpdating">
                    <div class="updateRoller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
                </div>
                <tbody class="logList" id="versionList"></tbody>
            </table>
        </div>`;

        document.getElementById('logTableHeader').style = 'background-color:#0226f0';
        printVersionLog();

        document.getElementById('schedulesWidgetBoxContainer').innerHTML += 
            '<div class="paginationBox">\
                <span class="pagination2 bi bi-caret-left-fill" onclick="schedulePreviousPage(' + 0 + ')"></span>\
                <span class="pagination">Page ' + (schedulePageNumber + 1) + ' of ' + totalPages + '</span>\
                <span class="pagination2 bi bi-caret-right-fill" onclick="scheduleNextPage(' + 0 + ')"></span>\
            </div>';
    }
}

function printVersionLog() {  // print version log
    
    // console.log("printVersionLog ------------ ");

    // document.getElementById('typeSort').style = 'color:#FFFFFF';
    // document.getElementById('equipSort').style = 'color:#FFFFFF';
    
    // console.log("version.length = " + version.length);
    totalPages = Math.ceil(version.length / scheduleTableLimit);  // round up to integer
    // console.log("totalPages = " + totalPages);
    if (totalPages == 0) {totalPages = 1;}

    if (schedulePageNumber >= totalPages) schedulePageNumber = 0;  // if we come to end of list go to page 1
    else if (schedulePageNumber < 0) schedulePageNumber = (totalPages - 1);  // go to last page when backing up
    // console.log("schedulePageNumber = " + schedulePageNumber);

    var s = schedulePageNumber * scheduleTableLimit;  // calculate start array location so correct page can print
    var p = 0;  // end of array location when printing schedule list
    
    // calculate end array location so correct page can print
    if (schedulePageNumber < totalPages-1) p = (schedulePageNumber * scheduleTableLimit) + scheduleTableLimit;  // if we are in middle of list
    else p = version.length;  // if we are at end of list get last array location

    // console.log("s = " + s);
    // console.log("p = " + p);

    for (var i=s; i < p; i++)  // draw each schedule to list
    {
        // console.log("version[i] = " + version[i]);
        
        const table = document.getElementById("versionList");

        let row = table.insertRow();
        row.id = "versionList_" + i;
        row.className = "scheduleTR";

        let expand = row.insertCell(0);
        expand.innerHTML = 
            '<div class="" id="versionExpandIcon_' + i + '" onclick="expandVersion(' + i + ')">\
                <div class="schedulesListIcon bi bi-arrow-90deg-down" title="View Schedule Details" style="font-size:8px; margin-left:8px;"></div>\
            </div>';

        let type = row.insertCell(1);
        type.innerHTML = version[i];
        type.setAttribute("onclick","expandVersion(" + i + ")");

        let equip = row.insertCell(2);
        equip.innerHTML = longDate(versionDate[i]);
        equip.setAttribute("onclick","expandVersion(" + i + ")");

        row = table.insertRow();  // 2nd row for schedule details
        row.id = "versionDetails_" + i;
        row.className = "schedulesContent";
    }
}

function printVersionDetails(arrayID) {  // print version details
    var versionType = [];
    var versionChange = [];
    console.log("arrayID = " + arrayID);

    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/getVersionDetails.php",
        cache: false,
        dataType: "json",
        data: {
            "i": versionID[arrayID]  // ID
        },
        success: function(dataWindow) {

            versionType = [];  // version number
            versionChange = [];  // version date release
            
            for (var i = 0; i < dataWindow.length; i++){
                versionType.push(dataWindow[i].versionType);
                versionChange.push(dataWindow[i].change);
            }
            
            // console.log("getVersionDetails--------------------------------------------------------------");
            // console.log(dataWindow);
            // console.log(versionType);
            // console.log(versionChange);

            document.getElementById("versionDetails_" + arrayID).innerHTML =  // 
            '<td colspan="19">\
                <div class="schedulesDetailsContainter" id="schedulesDetailsContainter_' + arrayID + '">\
                    <div class="scheduleDetails" id="scheduleDetails_' + arrayID + '">\
                    </div>\
                </div>\
            </td>';
        
            document.getElementById("scheduleDetails_" + arrayID).innerHTML += '</br>'; // 

            for (var i=0; i < versionType.length; i++)  // draw each schedule to list
            {
                document.getElementById("scheduleDetails_" + arrayID).innerHTML +=  // 
                `<b>` + versionType[i] + ` - </b>` + versionChange[i] + `</br>`;
            }

            document.getElementById("scheduleDetails_" + arrayID).innerHTML += '</br>'; // 
            document.getElementById("schedulesDetailsContainter_" + arrayID).style = 'border-bottom: 1px solid #000000;';  // 
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getVersionDetails');
        }
    });

}

function expandVersion(arrayID) {  // expand version details 
    // show or hide version details
    // console.log('expandVersion------');
    // console.log('arrayID                = ' + arrayID);
    // console.log('schedulePrevExpanded = ' + schedulePrevExpanded);
    var f = 0;  // flag to block collapse - if schedulePrevExpanded = arrayID OR if schedulePrevExpanded = null
    if (schedulePrevExpanded == null) {schedulePrevExpanded = arrayID; f = 1;}  // populate schedulePrevExpanded with current if null and flag so we don't collapse

    if (document.getElementById('versionDetails_' + arrayID).style.display != "contents") {  // expand current selection if it isn't open
        f = 1;  // set flag so we don't collapse current data in last step
        document.getElementById('versionList_' + arrayID).style.backgroundColor = "#00b610";  // change row background to green
        // document.getElementById('versionList_' + arrayID).style.border = "solid 1px rgb(165, 165, 165)";  // change row background to green
        document.getElementById('versionList_' + arrayID).style.color = "rgb(255, 255, 255)";  // change text color to white
        document.getElementById('versionDetails_' + arrayID).style.display = "contents";  // expand content
        document.getElementById('versionDetails_' + arrayID).style.marginBottom = "15px";  // add top margin
        document.getElementById('versionExpandIcon_' + arrayID).innerHTML =  // change collapse icon
            '<div class="schedulesListIcon bi bi-arrow-90deg-up" style="margin-left:8px; font-size:11px; color:#FFFFFF"></div>'
        printVersionDetails(arrayID);

        if (schedulePrevExpanded == arrayID) {f = 2;}  // if schedulePrevExpanded = arrayID set flag so we don't collapse in last step, this means the same row is being toggled twice or more
    }

    if ((f != 2) && (document.getElementById('versionDetails_' + schedulePrevExpanded).style.display === "contents")) {  // collapse previous content if open
        document.getElementById('versionList_' + schedulePrevExpanded).style.backgroundColor = "rgb(255, 255, 255)";  // change row background to white
        document.getElementById('versionList_' + schedulePrevExpanded).style.color = "rgb(0, 0, 0)";  // change text color to black
        document.getElementById('versionDetails_' + schedulePrevExpanded).style.marginBottom = "0px";  // remove bottom margin
        document.getElementById('versionDetails_' + schedulePrevExpanded).style.display = "none";  // collapse content
        document.getElementById('versionExpandIcon_' + schedulePrevExpanded).innerHTML =  // change collapse icon
            '<div class="schedulesListIcon bi bi-arrow-90deg-down" style="margin-left:8px; font-size:11px"></div>'
    }
    
    if ((schedulePrevExpanded == arrayID) && (f == 0)) {  // collapse current selection if another row is toggled while open
        document.getElementById('versionList_' + arrayID).style.backgroundColor = "rgb(255, 255, 255)";  // change row background to white
        document.getElementById('versionList_' + arrayID).style.color = "rgb(0, 0, 0)";  // change text color to black
        document.getElementById('versionDetails_' + arrayID).style.marginBottom = "0px";  // remove bottom margin
        document.getElementById('versionDetails_' + arrayID).style.display = "none";  // collapse content
        document.getElementById('versionExpandIcon_' + arrayID).innerHTML =  // change collapse icon
            '<div class="schedulesListIcon bi bi-arrow-90deg-down" style="margin-left:8px; font-size:11px"></div>'
    }
    schedulePrevExpanded = arrayID;  // track last row expanded
    // console.log('');
}

function updateTempCorF(value) {  // update if temperature is celsius or fahrenheit
    // console.log('updateTempCorF');
    // console.log(board);
    if ((enableButtonPressed == 0) && (tempCorF != value)) {  // add 1000ms delay after button is pressed
        var command = "3," + value;
        sendToBackend(command);  // send command to backend

        tempCorF = value;  // store board type

        if (tempCorF == 0) {
            // $("#celsius").prop("checked", true);  // mark radio button checked
            document.getElementById("fahrenheit").disabled = true;
            document.getElementById("celsius").checked = true;
        }
        else if (tempCorF == 1) {
            // $("#fahrenheit").prop("checked", true);  // mark radio button checked
            document.getElementById("celsius").disabled = true;
            document.getElementById("fahrenheit").checked = true;
        }
        enableButtonPressed = 1;
        setTimeout(function(){enableButtonPressed = 0; document.getElementById("fahrenheit").disabled = false; document.getElementById("celsius").disabled = false;},1000);  // button can't be pressed again for 500 millis
    }
}

function updateTimeFormat(value) {  // update time - 12hr or 24hr
    // console.log('updateTimeFormat');
    // console.log(board);
    if ((enableButtonPressed == 0) && (timeFormat != value)) {  // add 1000ms delay after button is pressed
        var command = "5," + value;
        sendToBackend(command);  // send command to backend

        timeFormat = value;  // store board type

        if (timeFormat == 0) {
            document.getElementById("12hour").disabled = true;
            document.getElementById("24hour").checked = true;
        }
        else if (timeFormat == 1) {
            document.getElementById("24hour").disabled = true;
            document.getElementById("12hour").checked = true;
        }
        enableButtonPressed = 1;
        setTimeout(function(){enableButtonPressed = 0; document.getElementById("12hour").disabled = false; document.getElementById("24hour").disabled = false;},1000);  // button can't be pressed again for 500 millis
    }
}

function updateAutoUpdate(value) {  // update temperature - celsius or fahrenheit
    // console.log('updateAutoUpdate');
    // console.log(value);
    if ((enableButtonPressed == 0) && (autoUpdate != value)) {  // add 1000ms delay after button is pressed
        var command = "993," + value;
        sendToBackend(command);  // send command to backend

        autoUpdate = value;

        if (autoUpdate == 0) {
            document.getElementById("autoUpdateBox").innerHTML =  // mark radio button checked
                `<div class="systemSettingBoxLabel">Auto Update</div>\
                <div class="control-group">\
                    <label class="control control-radio">\
                        On\
                            <input type="radio" name="autoUpdate" id="updateOn" class="updateOn" onclick="updateAutoUpdate(1)" />\
                        <div class="control_indicator"></div>\
                    </label>\
                    <label class="control control-radio">\
                        Off\
                            <input type="radio" name="autoUpdate" id="updateOff" class="updateOff" onclick="updateAutoUpdate(0)" />\
                        <div class="control_indicator"></div>\
                    </label>\
                    <p style="margin-top:17px"><b>Running Version </b>` + appVersion + `</p>\
                </div>\
                <button class='button _wide' id='manualUpdateButton' style='width:175px; margin:20px 0px 15px 0px;' type='button' onclick='manualUpdate()'>Check for Update</button>
                <button class="button _wide" style="width:175px; margin:6px 0px 0px 0px;" type="button" onclick="versionLog()">Version Log</button>`;

            document.getElementById("updateOn").disabled = true;
            document.getElementById("updateOff").checked = true;
            document.getElementById('autoUpdateBox').style.height = "195px";
        }
        else if (autoUpdate == 1) {
            document.getElementById("autoUpdateBox").innerHTML =  // mark radio button checked
                `<div class="systemSettingBoxLabel">Auto Update</div>\
                <div class="control-group">\
                    <label class="control control-radio">\
                        On\
                            <input type="radio" name="autoUpdate" id="updateOn" class="updateOn" onclick="updateAutoUpdate(1)" />\
                        <div class="control_indicator"></div>\
                    </label>\
                    <label class="control control-radio">\
                        Off\
                            <input type="radio" name="autoUpdate" id="updateOff" class="updateOff" onclick="updateAutoUpdate(0)" />\
                        <div class="control_indicator"></div>\
                    </label>\
                <p style="margin-top:17px"><b>Running Version </b>` + appVersion + `</p>
                </div>
                <button class="button _wide" style="width:175px; margin:20px 0px 0px 0px;" type="button" onclick="versionLog()">Version Log</button>`;

            document.getElementById("updateOff").disabled = true;
            document.getElementById("updateOn").checked = true;
            document.getElementById('autoUpdateBox').style.height = "138px";
        }
        enableButtonPressed = 1;
        setTimeout(function(){enableButtonPressed = 0; document.getElementById("updateOn").disabled = false; document.getElementById("updateOff").disabled = false;},1000);  // button can't be pressed again for 500 millis
    }
}

function updateRoboTankVersionConfirm(value) {  // update Robo-Tank version - v1, v2 or v3
    if (controllerVersion != value) {  // add 1000ms delay after button is pressed
        $('#popupBackground').show();  // grey out background
        $('.ds18b20Popup-body').empty();
        ds18b20Popup.style.display = "block";
        document.querySelector("body").style.overflow = 'hidden';
        $('.ds18b20PopupHeader').empty();

        $(".ds18b20PopupHeader").append("Restart Robo-Tank");
        $(".ds18b20Popup-body").append(
            '<div style="text-align: center;">\
                <p>&nbsp;</p>\
                <p>A restart is required to change the Robo-Tank controller version!</p>\
                <p>Would you like to restart Robo-Tank now?</p>\
                <div class="widgetButtonBox" id="widgetButtonBox">\
                    <button class="button _wide" type="button" onclick="updateRoboTankVersion(' + value + ')">Yes</button>\
                    <button class="button _wide" type="button" onclick="closeDs18b20Popup()">No</button>\
                </div></br>\
            </div>');
        }
}

function updateRoboTankVersion(value) {  // update Robo-Tank version - v1, v2 or v3
        
    document.getElementById("connectedIcon").src = "images/icons/disconn.png";
    console.log('updateRoboTankVersion = ' + value);
    $('.ds18b20PopupHeader').empty();
    $('.ds18b20Popup-body').empty();

    $(".ds18b20PopupHeader").append("Restarting Robo-Tank");
    $(".ds18b20Popup-body").append(
        '<div style="text-align: center;">\
            <p>&nbsp;</p>\
            <p style="font-weight:bold">Restarting Robo-Tank...</p>\
            <p>When the controller comes back online this message will disappear.</p>\
            <div class="updateRoller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>\
            <p>&nbsp;</p>\
        </div>');

    var command = "8," + value;
    sendToBackend(command);  // send command to backend

    controllerVersion = value;  // store board type

    if (controllerVersion == 0) {
        document.getElementById("version1").checked = true;
        document.getElementById("version2").disabled = true;
        document.getElementById("version3").disabled = true;
    }
    else if (controllerVersion == 1) {
        document.getElementById("version1").disabled = true;
        document.getElementById("version2").checked = true;
        document.getElementById("version3").disabled = true;
    }
    else if (controllerVersion == 2) {
        document.getElementById("version1").disabled = true;
        document.getElementById("version2").disabled = true;
        document.getElementById("version3").checked = true;
    }
    enableButtonPressed = 1;
    
    setTimeout(function(){  // button can't be pressed again for 500 millis
        enableButtonPressed = 0;
        document.getElementById("connectedIcon").src = "images/icons/disconn.png";
        document.getElementById("version1").disabled = false;
        document.getElementById("version2").disabled = false;
        document.getElementById("version3").disabled = false;
    },1000);
}

function changeRTCdateTime(m, d, y, h, M, dow) {  // save new date and time
    // console.log("changeRTCdateTime ----------------------");
    if (m != undefined) {  // only update if valid info
        dateData[0] = m;
        dateData[1] = d;
        dateData[2] = y;
        dateData[3] = h;
        dateData[4] = M;
        dateData[5] = dow;
    }
}

function saveRTCdateTime() {  // save new date and time
    // console.log("saveRTCdateTime ----------------------");
    // save new date and time - second, minute, hour, dayOfWeek, dayOfMonth, month, year
    var command = "995,0," + dateData[4] + "," + dateData[3] + "," + dateData[5] + "," + dateData[1] + "," + dateData[0] + "," + dateData[2];
    sendToBackend(command);  // send command to backend
    settingsSystem();
}

function updateRTCdateTime() {  // open window to set date and time
    printHeaderTitle("SYSTEM SETTINGS", "settings2.png", "#ff7800");  // name and file
    removeFooter();
    displayScreen = 8;

    
    document.getElementById('content').innerHTML +=
        `<div class='cleanScreen' id='cleanScreen'>\
            <div class='settingsContainer' id='settingsContainer'>\
                <div class="settingsTitle">Set the backup clock date and time!</div>\
                <div style="" id="updateDateTime"></div>\
                <div class="widgetButtonBox" id="widgetButtonBox">\
                    <button class="button _wide" type="button" onclick="saveRTCdateTime()">Save</button>\
                    <button class="button _wide" type="button" onclick="settingsSystem()">Cancel</button>\
                </div></br>\
            </div>\
        </div>`;

    var dateObj = new Date();    
    var m = dateObj.getMonth() + 1; //months from 1-12
    var d = dateObj.getDate();
    var y = dateObj.getFullYear() - 2000;
    var h = dateObj.getHours();
    var M = dateObj.getMinutes();
    var dow = dateObj.getDay() + 1;
    changeRTCdateTime(m, d, y, h, M, dow);

    if (timeFormat == 1) {
        var config = {
            target: 'updateDateTime',         // ID of HTML element
            timestamp: dateObj.getTime(),
            future: false,  // Only dates in the future,
            smartHours: true,  // Make a smart switch from AM to PM
            animations: true,
            disableAmPm: false,  // 12 hour clock

            months: {
            min: 0,
            max: 11,
            step: 1
            },
            minutes: {
            min: 0,
            max: 59,
            step: 1
            },
            years: {
            min: 2022,
            max: 2030,
            step: 1
            }
        };
    }
    else {
        var config = {
            target: 'updateDateTime',         // ID of HTML element
            timestamp: dateObj.getTime(),
            future: false,  // Only dates in the future,
            smartHours: true,  // Make a smart switch from AM to PM
            animations: true,
            disableAmPm: true,  // 24 hour clock

            months: {
            min: 0,
            max: 11,
            step: 1
            },
            minutes: {
            min: 0,
            max: 59,
            step: 1
            },
            years: {
            min: 2022,
            max: 2030,
            step: 1
            }
        };
    }
    var myDatepicker = new MtrDatepicker(config);  // configure datepicker
    var datepickerOutput = myDatepicker.toLocaleString();  // get current date/time string from datepicker

    myDatepicker.onChange('all', function() {  // run when date or time is changed, updates time string to be sent to backend
        datepickerOutput = myDatepicker.toLocaleString();
        console.log(datepickerOutput);

        var dateObj = new Date(datepickerOutput);
        var m = dateObj.getMonth() + 1; //months from 1-12
        var d = dateObj.getDate();
        var y = dateObj.getFullYear() - 2000;
        var h = dateObj.getHours();
        var M = dateObj.getMinutes();
        var dow = dateObj.getDay() + 1;
        changeRTCdateTime(m, d, y, h, M, dow);
    });
}
