var loadedGraphs = 0;
function printGraphs()  // print layout for graphs on home page and graph page
{
    if ((displayScreen == 0) || (displayScreen == 7)) {
        // console.log('graphVisible[i] = ' + graphVisible);
        var graphID = 0;  // count through all possible graphs
        $('#widgetDs18b20Graph').empty();  // clear div so we can print to it

        for (var i = 0; i < ds18b20Saved; i++) {  // create div for each ds18b20 graph being viewed
            if (graphVisible[i] == 1) {  // check if graph should be loaded
                document.getElementById("widgetDs18b20Graph").innerHTML += 
                    "<div class='widgetEachGraph'>\
                        <div class='dashboardGraphHeader' id='dashboardGraphHeader_" + graphID + "'>\
                            <div class='dashboardRollAverage' id='graphAverageLabel_" + graphID + "'>MA</div>\
                            <div class='dashboardGraphRange' id='graphAverageBox_" + graphID + "'>\
                                <input type='text' class='graphAverageField' id='graphAverage_" + graphID + "' value='" + graphAverage[graphID] + "' onfocus='showGraphHeader(0," + graphID + ")' onblur='showGraphHeader(1," + graphID + ")' onChange='changeGraphRollPeriod(0," + graphID + "," + i + ")' autocomplete='off'>\
                            </div>\
                            <div class='dashboardGraphRange' id='graphRange_0_" + graphID + "' onclick='changeGraphView(0,0," + graphID + "," + i + ")'>1h</div>\
                            <div class='dashboardGraphRange' id='graphRange_1_" + graphID + "' onclick='changeGraphView(0,1," + graphID + "," + i + ")'>6h</div>\
                            <div class='dashboardGraphRange' id='graphRange_2_" + graphID + "' onclick='changeGraphView(0,2," + graphID + "," + i + ")'>24h</div>\
                            <div class='dashboardGraphRange' id='graphRange_3_" + graphID + "' onclick='changeGraphView(0,3," + graphID + "," + i + ")'>3</div>\
                            <div class='dashboardGraphRange' id='graphRange_4_" + graphID + "' onclick='changeGraphView(0,4," + graphID + "," + i + ")'>7</div>\
                            <div class='dashboardGraphRange' id='graphRange_5_" + graphID + "' onclick='changeGraphView(0,5," + graphID + "," + i + ")'>14</div>\
                            <div class='dashboardGraphRange' id='graphRange_6_" + graphID + "' onclick='changeGraphView(0,6," + graphID + "," + i + ")'>30</div>\
                            <div class='dashboardGraphRange' id='graphRange_7_" + graphID + "' onclick='changeGraphView(0,7," + graphID + "," + i + ")'>90</div>\
                            <div class='dashboardGraphName' id='graphName_" + graphID + "'>" + ds18b20Name[i] + "</div>\
                        </div>\
                        <div id='graphDiv_" + graphID + "' style='width:100%; height:201px;'></div>\
                    </div>";
            }
            graphID++;
        }

        for (var i = 0; i < phSaved; i++) {  // create div for each pH graph being viewed
            if (graphVisible[graphID] == 1) {  // check if graph should be loaded
                document.getElementById("widgetDs18b20Graph").innerHTML += 
                    "<div class='widgetEachGraph'>\
                        <div class='dashboardGraphHeader' id='dashboardGraphHeader_" + graphID + "'>\
                            <div class='dashboardRollAverage' id='graphAverageLabel_" + graphID + "'>MA</div>\
                            <div class='dashboardGraphRange' id='graphAverageBox_" + graphID + "'>\
                                <input type='text' class='graphAverageField' id='graphAverage_" + graphID + "' value='" + graphAverage[graphID] + "' onfocus='showGraphHeader(0," + graphID + ")' onblur='showGraphHeader(1," + graphID + ")' onChange='changeGraphRollPeriod(1," + graphID + "," + i + ")' autocomplete='off'>\
                            </div>\
                            <div class='dashboardGraphRange' id='graphRange_0_" + graphID + "' onclick='changeGraphView(1,0," + graphID + "," + i + ")'>1h</div>\
                            <div class='dashboardGraphRange' id='graphRange_1_" + graphID + "' onclick='changeGraphView(1,1," + graphID + "," + i + ")'>6h</div>\
                            <div class='dashboardGraphRange' id='graphRange_2_" + graphID + "' onclick='changeGraphView(1,2," + graphID + "," + i + ")'>24h</div>\
                            <div class='dashboardGraphRange' id='graphRange_3_" + graphID + "' onclick='changeGraphView(1,3," + graphID + "," + i + ")'>3</div>\
                            <div class='dashboardGraphRange' id='graphRange_4_" + graphID + "' onclick='changeGraphView(1,4," + graphID + "," + i + ")'>7</div>\
                            <div class='dashboardGraphRange' id='graphRange_5_" + graphID + "' onclick='changeGraphView(1,5," + graphID + "," + i + ")'>14</div>\
                            <div class='dashboardGraphRange' id='graphRange_6_" + graphID + "' onclick='changeGraphView(1,6," + graphID + "," + i + ")'>30</div>\
                            <div class='dashboardGraphRange' id='graphRange_7_" + graphID + "' onclick='changeGraphView(1,7," + graphID + "," + i + ")'>90</div>\
                            <div class='dashboardGraphName' id='graphName_" + graphID + "'>" + phName[i] + "</div>\
                        </div>\
                        <div id='graphDiv_" + graphID + "' style='width:100%; height:201px;'></div>\
                    </div>";
            }
            graphID++;
        }

        for (var i = 0; i < graphID; i++) {  // go through each graph to add color to selected range buttons
            for (var r = 0; r < 8; r++) {  // go through each range and find match
                var div = document.getElementById('graphRange_' + r + '_' + i);  // find div on page
                if (div != null) {  // if div exists go on
                    if (graphRange[i] == r) {  // search for the button that matches the range
                        document.getElementById('graphRange_' + r + '_' + i).style.backgroundColor = "#00b610";  // add color to range button
                        break;
                    }
                }
            }
        }

        graphID = 0;  // count through all chart options
        for (var i = 0; i < ds18b20Saved; i++) {  // load graphs
            if (graphVisible[i] == 1) {  // check if graph should be loaded
                drawGraph(0, graphID, i);
            }
            graphID++;
        }

        for (var i = 0; i < phSaved; i++) {  // load graphs
            if (graphVisible[graphID] == 1) {  // check if graph should be loaded
                drawGraph(1, graphID, i);
            }
            graphID++;
        }
    }
}

function showGraphHeader(action, arrayID) {  // used to keep graph header visible when editing rolling average, NEEDS WORK
    // console.log('showGraphHeader --------- ' + action);
    // $(".dashboardGraphRange").style = "display: block;";
    if (action == 0) {  // keep header visible as rolling average input is selected
        $("#graphRange_0_" + arrayID).css({display: "block"});
        $("#graphRange_1_" + arrayID).css({display: "block"});
        $("#graphRange_2_" + arrayID).css({display: "block"});
        $("#graphRange_3_" + arrayID).css({display: "block"});
        $("#graphRange_4_" + arrayID).css({display: "block"});
        $("#graphRange_5_" + arrayID).css({display: "block"});
        $("#graphRange_6_" + arrayID).css({display: "block"});
        $("#graphRange_7_" + arrayID).css({display: "block"});
        $("#graphAverageLabel_" + arrayID).css({display: "block"});
        $("#graphAverageBox_" + arrayID).css({display: "block"});
        $("#dashboardGraphHeader_" + arrayID).css({paddingLeft: "60px"});
    }
    else {  // hide header as user left rolling average input field
        $("#graphRange_0_" + arrayID).css({display: "none"});
        $("#graphRange_1_" + arrayID).css({display: "none"});
        $("#graphRange_2_" + arrayID).css({display: "none"});
        $("#graphRange_3_" + arrayID).css({display: "none"});
        $("#graphRange_4_" + arrayID).css({display: "none"});
        $("#graphRange_5_" + arrayID).css({display: "none"});
        $("#graphRange_6_" + arrayID).css({display: "none"});
        $("#graphRange_7_" + arrayID).css({display: "none"});
        $("#graphAverageLabel_" + arrayID).css({display: "none"});
        $("#graphAverageBox_" + arrayID).css({display: "none"});
        $("#dashboardGraphHeader_" + arrayID).css({paddingLeft: "0px"});
        
        $("#dashboardGraphHeader_" + arrayID).hover(function(){
            $(this).css("paddingLeft", "60px");
            $("#graphRange_0_" + arrayID).css({display: "block"});
            $("#graphRange_1_" + arrayID).css({display: "block"});
            $("#graphRange_2_" + arrayID).css({display: "block"});
            $("#graphRange_3_" + arrayID).css({display: "block"});
            $("#graphRange_4_" + arrayID).css({display: "block"});
            $("#graphRange_5_" + arrayID).css({display: "block"});
            $("#graphRange_6_" + arrayID).css({display: "block"});
            $("#graphRange_7_" + arrayID).css({display: "block"});
            $("#graphAverageLabel_" + arrayID).css({display: "block"});
            $("#graphAverageBox_" + arrayID).css({display: "block"});
        }, function() {
            $(this).css("paddingLeft", "0px");
            $("#graphRange_0_" + arrayID).css({display: "none"});
            $("#graphRange_1_" + arrayID).css({display: "none"});
            $("#graphRange_2_" + arrayID).css({display: "none"});
            $("#graphRange_3_" + arrayID).css({display: "none"});
            $("#graphRange_4_" + arrayID).css({display: "none"});
            $("#graphRange_5_" + arrayID).css({display: "none"});
            $("#graphRange_6_" + arrayID).css({display: "none"});
            $("#graphRange_7_" + arrayID).css({display: "none"});
            $("#graphAverageLabel_" + arrayID).css({display: "none"});
            $("#graphAverageBox_" + arrayID).css({display: "none"});
        });
    }
}

function changeGraphRollPeriod(type, arrayID, sensorID) {  // change rolling average for graph
    graphAverage[arrayID] = document.getElementById("graphAverage_" + arrayID).value;  // get value from text box

    if (type == 0) {  // ds18b20
        drawGraph(0, arrayID, sensorID);

        $.ajax({  // update database
            method: "POST",
            url: "/php/ds18b20SaveGraphAverage.php",
            dataType: "text/plain",
            data: {
                    "id": String(ds18b20AddrSaved[sensorID]), 
                    "v": graphAverage[arrayID]
            }
        });
    }
    else if (type == 1) {  // pH
        drawGraph(1, arrayID, sensorID);

        $.ajax({  // update database
            method: "POST",
            url: "/php/probeSaveGraphAverage.php",
            dataType: "text/plain",
            data: {
                    "id": String(phAddrSaved[sensorID]), 
                    "v": graphAverage[arrayID]
            }
        });
    }
}

function printGraphsScreen() {  // print layout for graphs screen
    removeFooter();
    displayScreen = 7;

    document.getElementById('content').innerHTML =  // create main page
        '<div class="cleanScreen" id="cleanScreen">\
            <div class="widgetDs18b20GraphOptionsBox" id="widgetDs18b20GraphOptionsBox"></div>\
            <div class="" id="widgetDs18b20Graph"></div>\
            <div class="widgetButtonBox">\
                <button class="button _48 home_48" onclick="loadLayout()"></button>\
            </div>\
        </div>';

    var graphID = 0;  // count through all graphs
    for (var i = 0; i < ds18b20Saved; i++) {  // create check boxes for ds18b20's so we can select which sensor graphs to view
        document.getElementById("widgetDs18b20GraphOptionsBox").innerHTML += 
            '<form>\
                <div class="widgetDs18b20GraphOptions">\
                    <input type="checkbox" onclick="updateGraphsBeingViewed(0,' + graphID + ',' + i + ')" id="graphs_' + graphID + '">\
                    <label for="graphs_' + graphID + '">&nbsp;' + ds18b20Name[i] + '</label>\
                </div>\
            </form>';
        graphID++;
    }

    for (var i = 0; i < phSaved; i++) {   // create check boxes for pH so we can select which sensor graphs to view
        document.getElementById("widgetDs18b20GraphOptionsBox").innerHTML += 
            '<form>\
                <div class="widgetDs18b20GraphOptions">\
                    <input type="checkbox" onclick="updateGraphsBeingViewed(1,' + graphID + ',' + i + ')" id="graphs_' + graphID + '">\
                    <label for="graphs_' + graphID + '">&nbsp;' + phName[i] + '</label>\
                </div>\
            </form>';
        graphID++;
    }
    
    graphID = 0;  // count through all charts
    for (var i = 0; i < ds18b20Saved; i++) {  // mark checkbox checked if needed
        if (graphVisible[i] == 1) {document.getElementById("graphs_" + i).checked = true;}
        graphID++;
    }
    
    for (var i = 0; i < phSaved; i++) {  // mark checkbox checked if needed
        if (graphVisible[graphID] == 1) {document.getElementById("graphs_" + graphID).checked = true;}
        graphID++;
    }

    printGraphs();
}

function drawGraph(type, id, sensorNum)  // load graph data
{
    if (dyGprah[id]) {dyGprah[id].destroy();}  // clear instance of graph

    var fileName = "";  // track csv filename for graphs
    var label = "";  // track label for legend on graphs
    if (type == 0) {  // ds18b20
        if (tempCorF == 0) {fileName = "/chartData/" + ds18b20AddrSaved[sensorNum] + "_C.csv";}
        else {fileName = "/chartData/" + ds18b20AddrSaved[sensorNum] + "_F.csv";}
        label = "Date";
    }
    else if (type == 1) {  // pH graph
        fileName = "/chartData/p" + phAddrSaved[sensorNum] + ".csv";
        label = "Value";
    }

    dyGprah[id] = new Dygraph(
        document.getElementById("graphDiv_" + id),
        fileName,
        {
            rollPeriod: graphAverage[id],
            colors: ['#ff0000'],
            drawPoints: false,
            showRoller: true,
            showRangeSelector: true,
            rangeSelectorHeight: 0,
            rangeSelectorPlotStrokeColor: '#ff0000',
            rangeSelectorPlotFillColor: 'blue',
            labels: ['Date', label],
            digitsAfterDecimal: 3,
            dateWindow: [
                +new Date() - graphDays[id] * graphHours[id] * 60 * 60 * 1000,  // view last 7 days
                +new Date()  // today
            ]
            // visibility: [true, true]
        }
    );
}

function changeGraphView(type, view, arrayID, sensorID)  // change range of data being displayed in graph 
{
    switch (view) {  // update graph range variables based on selection
        case 0: graphDays[arrayID] = 1; graphHours[arrayID] = 1; break;
        case 1: graphDays[arrayID] = 1; graphHours[arrayID] = 6; break;
        case 2: graphDays[arrayID] = 1; graphHours[arrayID] = 24; break;
        case 3: graphDays[arrayID] = 3; graphHours[arrayID] = 24; break;
        case 4: graphDays[arrayID] = 7; graphHours[arrayID] = 24; break;
        case 5: graphDays[arrayID] = 14; graphHours[arrayID] = 24; break;
        case 6: graphDays[arrayID] = 30; graphHours[arrayID] = 24; break;
        case 7: graphDays[arrayID] = 90; graphHours[arrayID] = 24; break;
    }
    graphRange[arrayID] = view;

    document.getElementById('graphRange_' + view + '_' + arrayID).style.backgroundColor = "#00b610";  // add color to range button

    if (type == 0) {  // ds18b20
        $.ajax({  // update database
            method: "POST",
            url: "/php/ds18b20SaveGraphRange.php",
            dataType: "text/plain",
            data: {
                    "id": String(ds18b20AddrSaved[sensorID]), 
                    "v": view
            }
        });
    }
    else if (type == 1) {  // pH
        $.ajax({  // update database
            method: "POST",
            url: "/php/probeSaveGraphRange.php",
            dataType: "text/plain",
            data: {
                    "id": String(phAddrSaved[sensorID]), 
                    "v": view
            }
        });
    }

    printGraphs();
}

function updateGraphsBeingViewed(type, arrayID, sensorID) {  // update the type of controller board being used
    if (graphVisible[arrayID] == 1) {graphVisible[arrayID] = 0;}  // marked graph not being viewed
    else {graphVisible[arrayID] = 1;} // mark graph as being viewed

    printGraphs();

    if (type == 0) {  // ds18b20
        $.ajax({  // update database
            method: "POST",
            url: "/php/ds18b20SaveGraphView.php",
            dataType: "text/plain",
            data: {
                    "id": String(ds18b20AddrSaved[sensorID]), 
                    "v": graphVisible[arrayID]
            }
        });
    }
    else if (type == 1) {  // pH
        $.ajax({  // update database
            method: "POST",
            url: "/php/probeSaveGraphView.php",
            dataType: "text/plain",
            data: {
                    "id": String(ds18b20AddrSaved[sensorID]), 
                    "v": graphVisible[arrayID]
            }
        });
    }
}