;(function() {
"use strict";

var UsageGraph = function ($, c3, d3, OktaAuth, Promise, jQuery, moment, msCrypto, encoding) {

}

UsageGraph.init = function (selector, accountMaid) {

    oktaClient = getClient(window.atob(oktaBaseUrl), window.atob(clientId), redirectUri);
    localStorage.setItem('ETag', '');
    monthlyGraph = true;
    maid = accountMaid;
    createHtml(selector);
    let tabChecked = false;
    let radioChecked = false;
    let tooltipOpen = false;
    let minusOneTabIndex = document.querySelectorAll("[tabindex='-1']");
    let zeroTabIndex = document.querySelectorAll("[tabindex='0']");
   
    $('input[name="peaktype"]:radio').on('change', function () {
        ShowUsageGraph();
    });
    $('ul.tabs li').click(function () {
        var tab_id = $(this).attr('data-tab');
        if (tab_id == "monthly-billing") {
            $('.peak-wrapper').css('display', 'none');
            monthlyGraph = true;
        }
        else {
            $('.peak-wrapper').css('display', 'inline-block');
            monthlyGraph = false;   
        }
        $('ul.tabs li').removeClass('current');
        $('.tab-content').removeClass('current');
        $(this).addClass('current');
        $("#" + tab_id).addClass('current');
        ShowUsageGraph();
    });

//   accessibility changes

    Array.from(document.querySelectorAll('[role="button"], [role="radio"], [role="tab"], [role="anchor"], [role="tooltip"], [role="accordion"], [role="closeButton"], [role="headertab"]')).forEach(function (btn) {

        btn.addEventListener('mousedown', function (evt) {
            $(evt.target).addClass("disablefocus");
        });

        btn.addEventListener('mouseup', function (evt) {
            $(evt.target).addClass("disablefocus");
        });

        btn.addEventListener('keydown', function (evt) {
            $(evt.target).removeClass("disablefocus");
            if (evt.keyCode == 9) {
                $(evt.target).removeClass("disablefocus");
                ResetTabindex();
                if (evt.target.getAttribute("role") === "tooltip") {
                    tooltipOpenClose();
                    if (tooltipOpen == true) {
                        evt.preventDefault();
                    }
                }
            }
            if (evt.keyCode == 13 || evt.keyCode == 32) {
                btn.click();
                evt.target.focus();
                if (evt.target.getAttribute("role") === "radio") {
                    var itemid = evt.target.getAttribute('id');
                    ChangeTabindex(itemid);
                }
                if (evt.target.getAttribute("role") === "tab") {
                    var tabid = evt.target.getAttribute('id');
                    ChangeTabindex(tabid);
                }
            }
          
        });
        
    });

    var acc = $('.Accordion-trigger');
    acc.unbind();
    acc.on("click", function () {
        this.classList.toggle("active");
          var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
            event.target.setAttribute("aria-expanded", "false");
        } else {
            panel.style.display = "block";
            event.target.setAttribute("aria-expanded", "true");
        }
    });

    function ChangeTabindex(itemid) {
        if (itemid === "checkmark-peak") {
            document.getElementById('checkmark-offpeak').setAttribute("tabindex", "-1");
            radioChecked = true;
        }
        else {
            document.getElementById('checkmark-offpeak').setAttribute("tabindex", "0");
        }
        if (itemid === "monthlytab") {
            document.getElementById('dailytab').setAttribute("tabindex", "-1");
            tabChecked = true;
        }
        else {
            document.getElementById('dailytab').setAttribute("tabindex", "0");
        }
    }
    function ResetTabindex() {
        if (radioChecked === true) {
            radioChecked = false;
        }
        else {
            document.getElementById('checkmark-peak').setAttribute("tabindex", "0");
            document.getElementById('checkmark-offpeak').setAttribute("tabindex", "0");
        }
        if (tabChecked === true) {
            tabChecked = false;
        }
        else {
            document.getElementById('monthlytab').setAttribute("tabindex", "0");
            document.getElementById('dailytab').setAttribute("tabindex", "0");
        }
    }

    function tooltipOpenClose() {
        if (tooltipOpen === true) {
            
            Array.from(document.querySelectorAll('[role]')).forEach(function (element) {
                element.setAttribute("tabindex", "-1");
            })

            document.getElementById('clsBtn').setAttribute("tabindex", "0");

            $("#clsBtn").addClass('tooltip-clsbtn');                             
        }
    }

    function ResetAlltabindex() {

        tooltipOpen = false;
        
        Array.from(document.querySelectorAll('[role]')).forEach(function (element) {
            element.removeAttribute("tabindex", "-1");
        })

        Array.from(minusOneTabIndex).forEach(function (element) {
            element.setAttribute("tabindex", "-1");
        })

        Array.from(zeroTabIndex).forEach(function (element) {
            element.setAttribute("tabindex", "0");
        })

        $("#clsBtn").removeClass('tooltip-clsbtn');
        
    }


   //  completed accessibility changes

    $('#learnmore').click(function () {
        conditionalLearnMoreURL();
    });

    $('.tooltiptext').tooltipster({
        animation: 'fade',
        delay: 200,
        trigger: 'click',
        contentAsHTML: true,
        theme: ['tooltipster-noir', 'tooltipster-noir-customized'],
        interactive: true,
        autoclose: true,
        functionReady: function (origin,tooltip) {
            $('.tooltiptext').attr('aria-hidden', false);
            tooltipOpen = true;
            Array.from(document.getElementsByClassName('icon-widgetclose')).forEach(function (btn) {
                btn.addEventListener('mousedown', function (evt) {
                    $(evt.target).addClass("disablefocus");
                });

                btn.addEventListener('mouseup', function (evt) {
                    $(evt.target).addClass("disablefocus");
                });

                btn.addEventListener('keydown', function (evt) {
                    $(evt.target).removeClass("disablefocus");
                    if (evt.keyCode == 9) {
                      
                    }
                    if (evt.keyCode == 13 || evt.keyCode == 32) {
                        btn.click();                    
                    }
                });
            });
            $('.icon-widgetclose').click(function () {
                var tooltipid = tooltip.origin.getAttribute('id');
                document.getElementById(tooltipid).setAttribute("tabindex", "0");
                $('.tooltiptext').tooltipster('hide');
                tooltipOpen = false;
                $('.tooltiptext').attr('aria-hidden', true);
                document.getElementById(tooltipid).focus();
                ResetAlltabindex();
            }); 

        },
        functionAfter: function () {
            tooltipOpen = false;
            ResetAlltabindex();
        }
    });

    ShowUsageGraph();
    if (window.innerWidth <= 768) {
        isMobileDevice = true;
    }
    else
        isMobileDevice = false;

}

if (navigator.userAgent.match(/Trident.*rv\:11\./)) {
    var prom = new Promise(function () {
        window.crypto = msCrypto;
    });

    prom.then(function () {
        encoding.encode("");
        new encodingIndexes();
    });
}

function conditionalLearnMoreURL() {

    if (accountType === "SPP") {
        window.open("https://wem-cm-t1.coned.com/home/accounts-billing/select-pricing?open_external=true", "_blank");
    }
    else {
        window.open("https://wem-cm-t1.coned.com/en/accounts-billing/smart-energy-usage?open_external=true", "_blank");
    }

}

var redirectUri = window.location.origin + window.location.pathname;
var monthlyContainerWidth;
var dailyContainerWidth;
var oktaClient;
//var authSuccess = runAuthenticationFlow(oktaClient, sessiontoken, scopes);
var currentDisplayedDivId = '';
var dailyheadertooltip = "<div class='close-btn'><a class='icon-widgetclose' id='clsBtn' tabindex='0' role='closeButton'></a></div><div>Peak: Noon to 8 p.m., Monday through Friday  <br> Off-peak: All other summer hours, plus holidays</div>";
var peaktooltip = "<div class='close-btn'><a class='icon-widgetclose' id='clsBtn' tabindex='0' role='closeButton'></a></div><div>Your usage based on how much electricity you used between 12 p.m. and 8 p.m. (excluding weekends and holidays).<br>Peak: Noon to 8 p.m., Monday through Friday</div>";
var offpeaktooltip = "<div class='close-btn'><a class='icon-widgetclose' id='clsBtn' tabindex='0' role='closeButton'></a></div><div>Your usage based on how much electricity you used during off-peak hours.</div>";
var monthlyheadertooltip = "<div class='close-btn'><a class='icon-widgetclose' id='clsBtn' tabindex='0' role='closeButton'></a></div><div>Usage for the month during peak and off-peak hours <br> Peak: Noon to 8 p.m., Monday through Friday <br>Off-Peak: All other hours, plus holidays</div>";
var monthlyPeakTooltip = "<div class='close-btn'><a class='icon-widgetclose' id='clsBtn' tabindex='0' role='closeButton'></a></div><div>Your total usage for the month based on the sum of your peak hours readings.<br> Peak: Noon to 8 p.m., Monday through Friday </div>";
var monthlyOffPeakTooltip = "<div class='close-btn'><a class='icon-widgetclose' id='clsBtn' tabindex='0' role='closeButton'></a></div><div>Your total usage for the month based on the sum of your off-peak hours readings.<br> Off-peak: All other hours, plus holidays </div>";
var isLoaderEnabled = false;
var timeoutFunc;
let accountType;

function ShowUsageGraph(url) { 
    openModal();
    timeoutFunc=window.setTimeout(function () {
        if (isLoaderEnabled) {
            closeModal(false,url);
        }
    }, loaderTimerInMiliseconds);

    if (monthlyGraph) {
        if ($('#chart-monthly').css('display') == "block") {
            if (url == undefined || url == null) {
                url = "/v2/ratepilot/visualizations/" + maid + "/monthlyusage?Count=" + monthlydesktopBarCounts + "&Index=" + monthlydesktopIndex;
            }
            else {
                monthlydesktopIndex = url.substr(url.lastIndexOf("=") + 1, url.length);             
            }
        }
        else if ($('#chart-monthly-mobile').css('display') == "block") {
            if (url == undefined || url == null) {
                url = "/v2/ratepilot/visualizations/" + maid + "/monthlyusage?count=" + monthlymobileBarCounts + "&Index=" + monthlymobileIndex;
            }
            else {
                monthlymobileIndex = url.substr(url.lastIndexOf("=") + 1, url.length);
            }
        }
       
    }
    else {
        var radioValue = $("input[name='peaktype']:checked").val();
        if ($('#chart-daily').css('display') == "block") {
           
            if (url == undefined || url == null) {
                url = "/v2/ratepilot/visualizations/" + maid + "/dailyusage/" + radioValue + "?count=" + dailywebCyclesCount + "&index=" + dailywebIndex;
            }
            else {
                dailywebIndex = url.substr(url.lastIndexOf("=") + 1, url.length);
            }
        }
        else if ($('#chart-daily-mobile').css('display') == "block") {
            if (url == undefined || url == null) {
                url = "/v2/ratepilot/visualizations/" + maid + "/dailyusage/" + radioValue + "/" + dailymobilePageIndex + "/" + dailymobilemaxPageSizeCount;
            }
            else {
                var slashindex = url.lastIndexOf("/");
                var subpeak = url.substr(url, slashindex);
                var index = subpeak.substr(subpeak.lastIndexOf("/") + 1, subpeak.length);
                dailymobilePageIndex = index;

            }
        }
       
    }


    getVisualizationsData(url);


}
function openModal() {
    isLoaderEnabled = true;
    document.getElementById('loader').style.display = 'block';

}
function closeModal(success, requestUrl) {
    isLoaderEnabled = false;
    clearTimeout(timeoutFunc);
    document.getElementById('loader').style.display = 'none';
    if (!success) {
        //ajax failed
        $('#graphcd-lg-blockontent').css({ display: 'none' });
        $('#errorstate').css({ display: 'block' });
        var currentperiod = moment().add(-1, 'months').format("MMM YYYY") + " - " + moment().format("MMM YYYY");
        $('#timeperiod').text(currentperiod)
        $('#timeperiod').attr('aria-label', currentperiod);
        var prev = $('.carousel-control-prev');
        var next = $('.carousel-control-next');
        next.unbind();
        prev.unbind();

        if (requestUrl == undefined || requestUrl == null) {
            prev.css('display', 'none');
            prev.on('click', function () {
                return false;
            });
            next.css('display', 'none');
            next.on("click", function () {
                return false;
            });
            return;
        }

        var pageIndex;
        var newpreviousurl;
        var newnexturl;
        var previouspath;
        //check if the request url is of daily mobile usage. handling separately because of url structure.
        if (!monthlyGraph && $('#chart-daily').css('display') != "block") {
            pageIndex = requestUrl.substr(requestUrl.length - 3, 1);
            newpreviousurl = requestUrl.substring(0, requestUrl.length - 3) + (parseInt(pageIndex) + 1) + "/" + dailymobilemaxPageSizeCount;
            newnexturl = requestUrl.substring(0, requestUrl.length - 3) + (parseInt(pageIndex) - 1) + "/" + dailymobilemaxPageSizeCount;
            previouspath = window.atob(baseUrl) + newpreviousurl;
        }
        else {
            pageIndex = requestUrl.substr(requestUrl.length - 1, 1);
            newpreviousurl = requestUrl.substring(0, requestUrl.length - 1) + (parseInt(pageIndex) + 1);
            newnexturl = requestUrl.substring(0, requestUrl.length - 1) + (parseInt(pageIndex) - 1);
            previouspath = window.atob(baseUrl) + newpreviousurl;
        }

        if (sessionStorage.getItem(previouspath) == undefined || sessionStorage.getItem(previouspath) == null) {
            prev.css('display', 'none');
            prev.on('click', function () {
                return false;
            });
        }
        else {
            prev.css({ display: 'inline-block' });
            prev.on("click", function () {
                ShowUsageGraph(newpreviousurl);
            });
        }


        if (pageIndex > 0) {
            next.css({ display: 'inline-block' });
            next.on("click", function () {
                ShowUsageGraph(newnexturl);
            });
        }
        else {
            next.css('display', 'none');
            next.on('click', function () {
                return false;
            });
        }



    }
    else {
        $('#graphcd-lg-blockontent').css({ display: 'block' });
        $('#errorstate').css({ display: 'none' });

    }
}
function updateUI(response) {
    var graphdata = response.data;
    var links = response.links;   
    UpdateGraphsAndCarouselLinks(graphdata, links);
    accountType = response.data.billIndicatorType;
}
function getVisualizationsData(relativePath) {  
        var path = window.atob(baseUrl) + relativePath;

    if (sessionStorage.getItem(path) == undefined || sessionStorage.getItem(path) == null)
    {
 
        var xhr = new XMLHttpRequest();         
            oktaClient.tokenManager.get('token')
                .then(function (token) {                
                    if (token == undefined) {
                        oktaClient.token.getWithoutPrompt({
                            responseType: ['id_token', 'token'],
                            scopes: scopes  // optional if the user has an existing Okta session
                        })
                            .then(function (tokens) {
                                oktaClient.tokenManager.add('token', tokens[0]);
                                oktaClient.tokenManager.add('id_token', tokens[1]);
                                makeApiCallForData(tokens[0], xhr, path, relativePath);
                            })
                            .catch(function () {
                                closeModal(false, relativePath);
                               
                            });
                                
                    }
                    else {
                        makeApiCallForData(token, xhr, path, relativePath);
                    }
                }).catch(function () {
                    closeModal(false, relativePath);
                  
                });
       

        }
        else {
            var item = sessionStorage.getItem(path);
            
        updateUI(JSON.parse(item));
        }
}
function makeApiCallForData(token, xhr, path, relativePath)
{  
    var accessToken = token.accessToken;
    var currentETag = localStorage.getItem('ETag');
    var authheader = "Bearer " + accessToken;
    xhr.withCredentials = true;

            xhr.addEventListener("readystatechange", function () {

                if (xhr.readyState === 4)
                {
                    if (xhr.responseText != "" && (xhr.status === 200 || xhr.status === 304))
                    {
                        var responseData = JSON.parse(xhr.responseText);

                        if (xhr.response.status == 304) {
                            //do nothing
                        }
                        else if (jQuery.isEmptyObject(responseData)) {
                            //No data for the graph we should put an error state.
                            closeModal(false, relativePath);
                        } else {
                            localStorage.setItem('ETag', xhr.getResponseHeader('ETag'));
                            sessionStorage.setItem(path, JSON.stringify(responseData));
                            updateUI(responseData);
                        }
                    }
                    else
                    {
                        closeModal(false, relativePath);
                    }
                }


            });

            xhr.addEventListener("error", function () {
                   
                closeModal(false, relativePath);
                });


            xhr.open("GET", path, true);
            xhr.setRequestHeader("Accept", "application/json");
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.setRequestHeader("Ocp-Apim-Subscription-Key", window.atob(subscriptionKey));
            xhr.setRequestHeader("Authorization", authheader);
            xhr.setRequestHeader("DCXAppMode", appmode);
            xhr.setRequestHeader("Access-Control-Allow-Origin", '*');
            xhr.setRequestHeader("If-None-Match", currentETag);
            xhr.send();

}
function UpdateGraphsAndCarouselLinks(data, links) {

        if (monthlyGraph) {
            $('#monthlyPeaktooltip').tooltipster('content', monthlyPeakTooltip);
            $('#monthlyOffPeaktooltip').tooltipster('content', monthlyOffPeakTooltip);

            $('#headerTooltip').tooltipster('content', monthlyheadertooltip);

        if ($('#chart-monthly').css('display') == "block") {
            currentDisplayedDivId = '#chart-monthly';

            $('#timeperiod').text(data.startdate + ' - ' + data.enddate);
            GenerateMonthlyWebGraph(data, monthlyContainerWidth);
        }
        else if ($('#chart-monthly-mobile').css('display') == "block") {
            currentDisplayedDivId = '#chart-monthly-mobile';
            $('#timeperiod').text(data.startdate + ' - ' + data.enddate);
            GenerateMonthlyMobileGraph(data);
        }
    }
        else {
        $('#headerTooltip').tooltipster('content', dailyheadertooltip);
        var radioValue = $("input[name='peaktype']:checked").val();

        if (radioValue.toLowerCase() == "peak") {
            $('#dailylegendtext').text("Usage During Peak Hours (kWh)");
            $('#dailylegendtooltip').tooltipster('content', peaktooltip);
            $('.legendIcon').attr('style', 'background-color:#069bd7');
            $('.label-peak').attr('style', 'color:rgb(0, 136, 43)');
            $('.label-offpeak').attr('style', 'color:#636363');
            $('#checkmark-peak').attr('aria-checked', 'true');
            $('#checkmark-offpeak').attr('aria-checked', 'false');
        }
        else {
            $('#dailylegendtext').text("Usage During Off-Peak Hours (kWh)");
            $('#dailylegendtooltip').tooltipster('content', offpeaktooltip);
            $('.legendIcon').attr('style', 'background-color:#023A9A');
            $('.label-offpeak').attr('style', 'color:rgb(0, 136, 43)');
            $('.label-peak').attr('style', 'color:#636363');
            $('#checkmark-peak').attr('aria-checked', 'false');
            $('#checkmark-offpeak').attr('aria-checked', 'true');
        }
        if ($('#chart-daily').css('display') == "block") {
            currentDisplayedDivId = '#chart-daily';
            $('#timeperiod').text(data.startdate + ' - ' + data.enddate);
            GenerateDailyWebGraph(data, dailyContainerWidth);
        }
        else if ($('#chart-daily-mobile').css('display') == "block") {
            currentDisplayedDivId = '#chart-daily-mobile';
            $('#timeperiod').text(data.startdate + ' - ' + data.enddate);
            GenerateDailyMobileGraph(data);
        }

    }
    var prev = $('.carousel-control-prev');
        var next = $('.carousel-control-next');
        next.unbind();
        prev.unbind();
    if (links.prev != null) {
        prev.css('display', 'inline-block');     
        prev.on('click', function () {
            ShowUsageGraph(links.prev);
        });
    } else {
        prev.css('display', 'none');
        prev.on('click', function () {
            return false;
        });
    }

    if (links.next != null) {
        next.css('display', 'inline-block');
        next.on("click", function () {
            ShowUsageGraph(links.next);
        });
    } else {
        next.css('display', 'none');
        next.on("click", function () {
            return false;
        });
    }
    UpdateCustomGraphProperties(currentDisplayedDivId, data);
    closeModal(true, null);
}
function resetyaxislabels() {
    d3.selectAll('#chart-monthly-mobile, #chart-monthly, #chart-daily, #chart-daily-mobile')
        .selectAll(".c3-axis").selectAll(".tick text tspan").attr('x', 4);
}
function UpdateCustomGraphProperties(VisibledisplayDiv, data) {

    // Set box styling attributes for y-axis values.
    d3.selectAll('#chart-monthly-mobile, #chart-monthly, #chart-daily, #chart-daily-mobile')
        .selectAll('.c3-axis-y')
        .selectAll('.tick')
        .insert('rect', 'text')
        .attr("width", "55")
        .attr('height', '15')
        .attr('x', '1')
        .attr('y', '-8');
    resetyaxislabels();

    d3.selectAll('#chart-monthly-mobile, #chart-monthly, #chart-daily, #chart-daily-mobile')
        .selectAll('svg')
        .attr('focusable', 'false')
        .attr('role', 'presentation');

    //Set custom styling properties for year separator line.
    if (d3.selectAll(VisibledisplayDiv).selectAll('.c3-xgrid-lines')
        .selectAll('.c3-xgrid-line').select('line')._groups[0].length > 0 && !monthlyGraph) {
        var x = d3.selectAll(VisibledisplayDiv).selectAll('.c3-xgrid-lines')
            .selectAll('.c3-xgrid-line').select('line')

            .attr('x1')
        var y = d3.selectAll(VisibledisplayDiv).selectAll('.c3-xgrid-lines')
            .selectAll('.c3-xgrid-line').select('line')

            .attr('y1')

        var xsize = parseInt(x, 10) + 4 * 8;

        d3.selectAll(VisibledisplayDiv).selectAll('.c3-xgrid-lines')
            .selectAll('.c3-xgrid-line')
            .attr('stroke', '#d7d7d7')
            .attr('fill', '#fff')
            .attr('font', '10px sans-serif')
            .attr('color', '#000')
            .attr('stroke-width', '.5')
            .insert('rect', 'text')
            .attr("width", '35')
            .attr('height', '15')
            .attr('x', x)
            .attr('y', y);

        d3.selectAll(VisibledisplayDiv).selectAll('.c3-xgrid-lines')
            .selectAll('.c3-xgrid-line')
            .selectAll('text')
            .attr('x', xsize)
            .attr('y', '16')
            .attr('transform', '');


    }
    else {
        AddYearSeparator(data);
    }


    $(window).off("resize");
    $(window).off("click");
    $(window).off("focus");

  
    window.addEventListener("resize", function () {
      
        if (monthlyGraph) {
            setTimeout(function () {
                resetyaxislabels();
                AddYearSeparator(data);
                monthlyContainerWidth = $('#chart-monthly').width();

            }, 100);
        }
        else {
            setTimeout(function () {

                refreshYearSeparator();
                dailyContainerWidth = $('#chart-daily').width();
            }, 500);
        }
       

    });
    window.addEventListener("click", function () {
        resetyaxislabels();
        if (monthlyGraph) {
            AddYearSeparator(data);
        }
        else {
            setTimeout(function () {
                refreshYearSeparator();

            }, 500);
        }
    });
    window.addEventListener("focus", function () {
        resetyaxislabels();
        if (monthlyGraph) {
            AddYearSeparator(data);
        }
        else {
            setTimeout(function () {
              refreshYearSeparator();

            }, 500);
        }

    });
    $(window).resize(function () {

        if (isMobileDevice && window.innerWidth >= 768) {
            ShowUsageGraph();
            isMobileDevice = false;
        }
        if (!isMobileDevice && window.innerWidth <= 768) {
            ShowUsageGraph();
            isMobileDevice = true;
        }

    })
}
function refreshYearSeparator() {
    if (d3.selectAll(currentDisplayedDivId).selectAll('.c3-xgrid-lines')
        .selectAll('.c3-xgrid-line').select('line')._groups[0].length > 0 && !monthlyGraph) {
        var x = d3.selectAll(currentDisplayedDivId).selectAll('.c3-xgrid-lines')
            .selectAll('.c3-xgrid-line').select('line')

            .attr('x1');

        var xsize = parseInt(x, 10) + 4 * 8;
        d3.selectAll(currentDisplayedDivId).selectAll('.c3-xgrid-lines')
            .selectAll('.c3-xgrid-line')
            .selectAll('text')
            .attr('x', xsize)
            .attr('y', '16')
            .attr('transform', '');
    }
}
function AddYearSeparator(data) {
    var isyearChange = false;
    var newYearFirstBillDate;
    var lastyearlastBillDate;

    for (var i = 1; i < data.x.length - 1; i++) {
        var templastdate = moment.parseZone(data.x[i], moment.ISO_8601);
        var tempcurrentDate = moment.parseZone(data.x[i + 1], moment.ISO_8601)
        if (templastdate.year() != tempcurrentDate.year()) {
            lastyearlastBillDate = templastdate;
            newYearFirstBillDate = tempcurrentDate;
            isyearChange = true;
        }
    }
    if (!isyearChange) return;
    var xNodes = d3.selectAll(currentDisplayedDivId).selectAll('tspan').filter(function () {
        return d3.select(this).text() ===
            newYearFirstBillDate.format("MMM DD");

    }).nodes();
    if (xNodes.length == 0) return;
    var newdatespantransform = xNodes[0].parentNode.parentNode.getAttribute('transform');


    var newdatespantransform
    var newDatexoffset = newdatespantransform.split('(')[1].split(',')[0].split(')')[0];

    var lastyeardatespantransform = d3.selectAll(currentDisplayedDivId).selectAll('tspan').filter(function () {
        return d3.select(this).text() ===
             lastyearlastBillDate.format("MMM DD");
           
    })
        .nodes()[0].parentNode.parentNode.getAttribute('transform');
    var lastDatexoffset = lastyeardatespantransform.split('(')[1].split(',')[0].split(')')[0];


    var daysdifference = (newYearFirstBillDate - lastyearlastBillDate) / (1000 * 60 * 60 * 24);
    var newyeardiff = Math.ceil((newYearFirstBillDate - moment.parseZone(new Date(newYearFirstBillDate.year(), 0, 1), moment.ISO_8601)) / (1000 * 60 * 60 * 24));
   
    var newxOffset = newDatexoffset - ((newDatexoffset - lastDatexoffset) / daysdifference * newyeardiff);


    var x = d3.selectAll(currentDisplayedDivId).selectAll('.c3-xgrid-lines');
    // if (x.selectAll('.c3-xgrid-line').nodes().length <8) {
   
    x.append('g').attr("class", "c3-xgrid-line text-line-year");
    var y = d3.selectAll(currentDisplayedDivId).selectAll('.c3-xgrid-lines').selectAll('.c3-xgrid-line');
    y.append('line').attr("x1", newxOffset).attr("x2", newxOffset).attr("y1", "0").attr("y2", "286").style("opacity", 1);
    y.insert('rect', 'text').attr("class", "line-rect")
        .attr("width", '35')
        .attr('height', '15')
        .attr('x', newxOffset)
        .attr('y', 0);
    y.append('text').attr("text-anchor", "end").attr("transform", "")
        .attr("x", newxOffset + 32).attr("y", "16").attr('dx', -4).attr('dy', -5).style("opacity", 1).text(newYearFirstBillDate.format("YYYY")) // udpate
    //  }
}
function getSeparatorValue(startDatestring, endDatestring) {
    var startDate = new Date(startDatestring);
    var endDate = new Date(endDatestring);
    var separatorvalue = null;
    if (startDate.getFullYear() != endDate.getFullYear()) {
        separatorvalue = new Date(endDate.getFullYear(), 0, 1);
    }
    return separatorvalue;
}
window.UsageGraph = UsageGraph;





function createHtml(selector) {
    var container = "<div class='container-wrapper'><div class='container'><div class='chart-caption text-center'> <a id='prev-control' class=' float-left carousel-control-prev' tabindex='0' role='button' alt='navigates to previous date range'>‹</a><h1 id='timeperiod' class='time-period' tabindex='0' role='headertab'></h1> <a id='next-control' class='float-right carousel-control-next' tabindex='0' role='button' alt='navigates to next date range'>›</a><h2 class='time-perfiod-info'> Peak and off-peak hours apply <a id='headerTooltip' class='icon-widgetmore-info tooltiptext' tabindex='0' role='tooltip'> </a></h2></div><div class='billing-cycle text-center'><ul class='tabs' role='tablist' aria-label='Chart Type Tabs'><li class='tab-link current monthly' data-tab='monthly-billing' role='tab' id='monthlytab' tabindex='0' >Monthly</li><li class='tab-link daily' data-tab='daily-billing' role='tab' id='dailytab' tabindex='0'>Daily</li> <span class='peak-wrapper'> <label class='container1 label-peak'> PEAK <input type='radio' checked='checked' name='peaktype' value='Peak' tabindex='-1' > <span class='checkmark' id='checkmark-peak' role='radio' tabindex='0' aria-checked='true'> </span> </label> <label class='container1 label-offpeak'> OFF-PEAK <input type='radio' name='peaktype' value='OffPeak' tabindex='-1' > <span class='checkmark' id='checkmark-offpeak' role='radio' tabindex='0' aria-checked='false'> </span> </label> </span></ul></div><div id='graphcd-lg-blockontent'><div id='monthly-billing' class='tab-content current panel' role='tabpanel' aria-labelledby='monthlytab'> <section class='usage-wrapper'><div id='chart-monthly' class='d-sm-none' aria-hidden='true' focusable='false' role='presentation'></div><div id='chart-monthly-mobile' class='d-lg-none' aria-hidden='true' focusable='false' role='presentation'></div><div class='legend '><table class='c3-tooltip' role='presentation'><tr class='customLegend'><td> <span style='background-color:#069bd7'> </span> Usage During Peak Hours (kWh) <a id='monthlyPeaktooltip' class='icon-widgetmore-info tooltiptext' tabindex='0' role='tooltip'> </a></td><td> <span style='background-color:#023A9A'> </span> Usage During Off-Peak Hours (kWh) <a id='monthlyOffPeaktooltip' class='icon-widgetmore-info tooltiptext' tabindex='0' role='tooltip'> </a></td></tr></table></div><div aria-expanded='false' class='Accordion-trigger' role='accordion' tabindex='0'> <span class='Accordion-title'> Show Your Usage <span class='Accordion-icon'></span> </span></div><div id='tbl' class='panel'></div> </section></div><div id='daily-billing' class='tab-content panel' role='tabpanel' aria-labelledby='dailytab'> <section class='usage-wrapper'><div id='chart-daily' class='d-none d-sm-none d-lg-block' aria-hidden='true' focusable='false' role='presentation'></div><div id='chart-daily-mobile' class='d-lg-none d-sm-block' aria-hidden='true' focusable='false' role='presentation'></div><div class='legend'><table class='c3-tooltip ' role='presentation'><tr class='customDailyLegend'><td scope='row'> <b class='legendIcon'>&nbsp;&nbsp;&nbsp;&nbsp;</b> <label id='dailylegendtext'> </label> <a id='dailylegendtooltip' class='icon-widgetmore-info tooltiptext' tabindex='0' role='tooltip'> </a></td></tr></table></div><div aria-expanded='false' class='Accordion-trigger' role='accordion' tabindex='0'> <span class='Accordion-title'> Show Your Usage <span class='Accordion-icon'></span> </span></div><div id='tbl-daily' class='panel'></div> </section></div></div><div id='errorstate' > <img src='" + errorimagepath + "' alt='Error Image'/><h2>We Can’t Get This Data Right Now</h2><p> Sorry. There seems to be a problem on our end. Refresh the page or try again at a later time.</p><p> If you're using Safari, please allow third-party cookies from conEd.com in your browser settings, or use a different browser.</p></div><div class='note-block'> <span class='header-note'> NOTE: </span>Usage is based on when you use electricity. To lower your usage, shift the use of large electric devices to off-peak hours. <span> <a class='tooltiptext no-custom-outline' id='learnmore' tabindex='0' role='anchor'>Learn more.</a> </span></div><div id='loader' class='modal'> <img src='" + loadimagepath + "' alt='Loading Image'/></div></div></div>";
    $(selector).html(container);
    monthlyContainerWidth = $('#chart-monthly').width();
    dailyContainerWidth = $('#chart-daily').width();
}

function getClient(issuer, clientId, redirectUri) {
    var authClient;
    //if (isMsie())
      //  window.crypto = window.msCrypto;

    var isPKCESupported = OktaAuth.features.isPKCESupported();
    var tokenUri = issuer + '/v1/token';

    if (isPKCESupported) {
        // Bootstrap the AuthJS Client
        var config = {
            // Org URL
            issuer: issuer,
            // OpenID Connect APP Client ID
            clientId: clientId,
            // Trusted Origin Redirect URI
            redirectUri: redirectUri,
            tokenUrl: tokenUri,
            pkce: true,
            storage: 'sessionStorage'
        };
        authClient = new OktaAuth(config);
    }
    else {
        //Error
    }

    return authClient;
}

//function runAuthenticationFlow(authClient, sessiontoken, scopelist) {
//    var success = false;

//    authClient.session.exists()
//        .then(function (exists) {
//            if (exists) {
//                //debugger;
//                authClient.token.getWithoutPrompt({
//                    responseType: ['id_token', 'token'],
//                    scopes: scopelist  // optional if the user has an existing Okta session
//                })
//                    .then(function (tokens) {
//                        //debugger;
//                        authClient.tokenManager.add('token', tokens[0]);
//                        authClient.tokenManager.add('id_token', tokens[1]);
//                        success = true;
//                    })
//                    .catch(function (error) {
//                        //debugger;
//                        success = false;
//                    });
//            }
//            else {

//                authClient.token.getWithoutPrompt({
//                    sessionToken: sessiontoken,
//                    scopes: scopelist  // optional if the user has an existing Okta session
//                })
//                    .then(function (tokens) {
//                        //debugger;
//                        authClient.tokenManager.add('token', tokens[0]);
//                        authClient.tokenManager.add('id_token', tokens[1]);
//                        success = true;
//                    })
//                    .catch(function (error) {
//                        success = false
//                    });
//            }
//        })
//        .catch(function (error) {
//            //debugger;
//            //Error
//            success = false;
//        });


//    return success;

//}

//function getAccessToken(authClient)
//{
//    var retValue;

//    authClient.tokenManager.get('token')
//        .then(function (token) {
//            retValue = token.accessToken;
//            return retValue;
//        })
//        .catch(function (err) {
//            return err;
//        });
    
//}

//function isMsie() {
//    var ua = window.navigator.userAgent;
//    var msie = ua.indexOf("MSIE ");

//    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer
//    {
//        return true;
//    }
//    else  // If another browser
//    {
//        return false;
//    }
//    return false;
//}

//array.from support for IE11
if (!Array.from) {
    Array.from = (function () {
        var toStr = Object.prototype.toString;
        var isCallable = function (fn) {
            return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
        };
        var toInteger = function (value) {
            var number = Number(value);
            if (isNaN(number)) { return 0; }
            if (number === 0 || !isFinite(number)) { return number; }
            return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
        };
        var maxSafeInteger = Math.pow(2, 53) - 1;
        var toLength = function (value) {
            var len = toInteger(value);
            return Math.min(Math.max(len, 0), maxSafeInteger);
        };

        // The length property of the from method is 1.
        return function from(arrayLike/*, mapFn, thisArg */) {
            // 1. Let C be the this value.
            var C = this;

            // 2. Let items be ToObject(arrayLike).
            var items = Object(arrayLike);

            // 3. ReturnIfAbrupt(items).
            if (arrayLike == null) {
                throw new TypeError("Array.from requires an array-like object - not null or undefined");
            }

            // 4. If mapfn is undefined, then let mapping be false.
            var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
            var T;
            if (typeof mapFn !== 'undefined') {
                // 5. else
                // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
                if (!isCallable(mapFn)) {
                    throw new TypeError('Array.from: when provided, the second argument must be a function');
                }

                // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
                if (arguments.length > 2) {
                    T = arguments[2];
                }
            }

            // 10. Let lenValue be Get(items, "length").
            // 11. Let len be ToLength(lenValue).
            var len = toLength(items.length);

            // 13. If IsConstructor(C) is true, then
            // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
            // 14. a. Else, Let A be ArrayCreate(len).
            var A = isCallable(C) ? Object(new C(len)) : new Array(len);

            // 16. Let k be 0.
            var k = 0;
            // 17. Repeat, while k < len… (also steps a - h)
            var kValue;
            while (k < len) {
                kValue = items[k];
                if (mapFn) {
                    A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
                } else {
                    A[k] = kValue;
                }
                k += 1;
            }
            // 18. Let putStatus be Put(A, "length", len, true).
            A.length = len;
            // 20. Return A.
            return A;
        };
    }());
}


function GenerateDailyWebGraph(webdailyvalues, widthValue) {


    var separatorValue = getSeparatorValue(webdailyvalues.startdate, webdailyvalues.enddate);
    var lines = [];
    if (separatorValue != null)
        lines = [{ value: separatorValue, text: separatorValue.getFullYear() }];
 c3.generate({
        bindto: '#chart-daily',
        size: {
            width: widthValue,

        },
        data: {
            x: 'x',
            xFormat: '%Y-%m-%dT%H:%M:%S.%L%L%L%Z',
            columns: [
                webdailyvalues.x,
                webdailyvalues.usage
            ],
            type: 'area',
            color: function (color, d) {
                if (d.id === 'Peak') {
                    return '#069bd7'
                } else {
                    return '#023A9A'
                }

            }


        },
        point: {
            r: 0,
            focus: { expand: { r: 5 } }
        },
        axis: {
            x: {
                type: 'timeseries',
                padding: {
                    left: 300000000,
                    right: 50000000
                },
                tick: {
                    outer: false,
                    culling: false,
                    //  count: 30,
                    format: '%d'
                }

            },
            y: {
                inner: true,
                center: 0,
                max: parseFloat(webdailyvalues.y[webdailyvalues.y.length - 1]),
                tick: {
                    format: function (d) { return (d) + " kWh"; },
                    outer: false,
                    values: webdailyvalues.y
                },
                padding: { top: 50 }
            }
        },


        grid: {
            lines: {
                front: false
            },
            y: {
                show: true
            },
            x: {
                lines: lines
            }
        },
        tooltip: {
            contents: function (d) {
                if (d) {
                    var usageType = 'Peak';

                    for (var i = 0; i < d.length; i++) {

                        if (i === 0)
                        {
                            if (webdailyvalues.usage[0] == 'Peak') {
                                usageType = 'peak';
                            } else {
                                usageType = 'off-peak';
                            }
                        }

                        var dailyDate = d[i].x.toLocaleDateString("en-US", options);
                        var daytype = 'weekend';
                        for (var j = 1; j < webdailyvalues.x.length; j++) {
                            if (new Date(webdailyvalues.x[j]).getTime() == d[i].x.getTime()) {
                                if (webdailyvalues.dayType != undefined) {
                                    daytype = webdailyvalues.dayType[j];
                                }
                            }
                        }
                        if (d[i].value === 0) {
                            if (usageType.toLowerCase() == "off-peak") {
                                return '<div class="tooltip-container"><table class="c3-tooltip dailyTooltip"><tbody><tr class=""><th colspan="2">' + dailyDate + '</th></tr><tr><td class="name">Usage appears as <label class="chart-tooltip-bold">0 kWh</label> because of a system issue.</td></tr></tbody></table> </div>';
                            }
                            else if (usageType.toLowerCase() == "peak") {
                                return '<div class="tooltip-container"><table class="c3-tooltip dailyTooltip"><tbody><tr class=""><th colspan="2">' + dailyDate + '</th></tr><tr><td class="name">Usage appears as <label class="chart-tooltip-bold">0 kWh</label> during weekends and holidays, or during system issues.</td></tr></tbody></table> </div>';
                            }
                        }
                        else {
                            return '<div class="tooltip-container"><table class="c3-tooltip dailyTooltip"><tbody><tr class=""><th colspan="2">' + dailyDate + '</th></tr><tr><td class="name">Your total usage during ' + usageType.toLowerCase() + ' hours for the day was <b class="value">' + d[i].value + ' kWh</b></td></tr></tbody></table></div>';
                        }
                    }
                }

            }
        },
        legend: {
            show: false
        }
    });

    if (webdailyvalues != null || webdailyvalues != {}) {

        var div = document.createElement('div');
        div.setAttribute("id", "tbl-daily");
        document.body.appendChild(div);

        var existingtable = document.getElementById("dailytable")

        if (existingtable) {
            document.getElementById("tbl-daily").removeChild(existingtable)
        }
        document.getElementById("tbl-daily").appendChild(buildTable(webdailyvalues));

        function buildTable(data) {
            var dailyusageType = data.usage[0];
            var table = document.createElement("table");
            table.setAttribute("class", "gridtable");
            table.setAttribute("id", "dailytable");
            var thead = document.createElement("thead");
            var tbody = document.createElement("tbody");
            var headRow = document.createElement("tr");
            if (dailyusageType === "Peak") {
                ["Date", "Usage During Peak Hours (kWh)"].forEach(function (el) {
                    var th = document.createElement("th");
                    th.setAttribute("scope", "col");
                    th.appendChild(document.createTextNode(el));
                    headRow.appendChild(th);
                });
            }
            else if (dailyusageType === "OffPeak") {
                ["Date", "Usage During Off-Peak Hours (kWh)"].forEach(function (el) {
                    var th = document.createElement("th");
                    th.setAttribute("scope", "col");
                    th.appendChild(document.createTextNode(el));
                    headRow.appendChild(th);
                });
            }
            thead.appendChild(headRow);
            table.appendChild(thead);

            var days = data.x;
            var usage = data.usage;

            for (var i = days.length - 1; i > 0; i--) {

                var formattedDate = moment.parseZone(days[i], moment.ISO_8601).format("MMM DD,YYYY");
                var tr = document.createElement("tr");
                var td = document.createElement("td");
                td.setAttribute("scope", "row");
                td.appendChild(document.createTextNode(formattedDate))
                tr.appendChild(td);
                var td1 = document.createElement("td");
                td1.setAttribute("scope", "row");
                td1.appendChild(document.createTextNode(usage[i]))
                tr.appendChild(td1);
                tbody.appendChild(tr);
            }
            table.appendChild(tbody);
            return table;
        }
    }

    // Custom Legend
    //d3.select('.customDailyLegend').selectAll('span')
    //    .data(dailyLegendData)
    //    .enter().append('td').append('label').attr('data-id', function (id) {
    //        return id;
    //    })
    //    .html(function (id) {
    //        return '<span>&nbsp;&nbsp;&nbsp;&nbsp;</span>' + id;

    //    }).each(function (id) {
    //        d3.select(this).select('span').style('background-color', dailyDesktop.color(id));
    //    })
    //    .on('mouseover', function (id) {
    //        dailyDesktop.focus(id);
    //    })
    //    .on('mouseout', function (id) {
    //        dailyDesktop.revert();
    //    })

    //d3.select('.customDailyLegend').selectAll('td').append('a').attr('class', 'i-icon').text('i').on('mouseover', function (id) {
    //    $(this).find('b').css('display', 'block').text('Your usage based on how much electricity you used between 12 p.m. and 8 p.m. (excluding weekends and holidays).Peak: Noon to 8 p.m., Monday through Friday');
    //}).append('b').attr('class', 'tooltiptext')
}

function GenerateDailyMobileGraph(mobiledailyvalues) {


    var separatorValue = getSeparatorValue(mobiledailyvalues.startdate, mobiledailyvalues.enddate);
    var lines = [];
    if (separatorValue != null)
        lines = [{ value: separatorValue, text: separatorValue.getFullYear() }];

    c3.generate({
        bindto: '#chart-daily-mobile',
        size: {
            //width: 280
        },

        data: {
            x: 'x',
            xFormat: '%Y-%m-%dT%H:%M:%S.%L%L%L%Z',
            columns: [
                mobiledailyvalues.x,
                mobiledailyvalues.usage
            ],
            type: 'area',
            color: function (color, d) {
                if (d.id === 'Peak') {
                    return '#069bd7'
                } else {
                    return '#023A9A'
                }

            }
        },
        point: {
            r: 0,
            focus: { expand: { r: 5 } }
        },
        axis: {
            x: {
                padding: {
                    left: 120000000,
                    right: 20000000
                },
                type: 'timeseries',
                tick: {
                    culling: false,
                    //  count: 30,
                    format: '%d'
                }

            },
            y: {
                padding: { top: 50 },
                inner: true,
                center: 0,
                max: parseFloat(mobiledailyvalues.y[mobiledailyvalues.y.length - 1]),
                tick: {
                    format: function (d) { return d + " kWh"; },
                    outer: false,
                    values: mobiledailyvalues.y
                }
            }
        },
        grid: {
            lines: {
                front: false
            },
            y: {
                show: true
            },
            x: {
                lines: lines
            }
        },
        tooltip: {
            contents: function (d) {
                if (d) {
                    var usageText = 'Peak';

                    for (var i = 0; i < d.length; i++) {

                        if (i === 0) {
                            if (mobiledailyvalues.usage[0] == 'Peak')
                            {
                                usageText = 'peak';
                            } else {
                                usageText = 'off-peak';
                            }
                        }

                        var dailyDate = d[i].x.toLocaleDateString("en-US", options);
                        var daytype = 'weekend';
                        for (var j = 1; j < mobiledailyvalues.x.length; j++) {
                            if (new Date(mobiledailyvalues.x[j]).getTime() == d[i].x.getTime()) {
                                if (mobiledailyvalues.dayType != undefined) {
                                    daytype = mobiledailyvalues.dayType[j];
                                }
                            }
                        }
                        if (d[i].value === 0) {
                            if (usageText.toLowerCase() == "off-peak") {
                                return '<div class="tooltip-container"><table class="c3-tooltip dailyTooltip"><tbody><tr class=""><th colspan="2">' + dailyDate + '</th></tr><tr><td class="name">Usage appears as <label class="chart-tooltip-bold">0 kWh</label> because of a system issue.</td></tr></tbody></table> </div>';
                            }
                            else if (usageText.toLowerCase() == "peak") {
                                return '<div class="tooltip-container"><table class="c3-tooltip dailyTooltip"><tbody><tr class=""><th colspan="2">' + dailyDate + '</th></tr><tr><td class="name">Usage appears as <label class="chart-tooltip-bold">0 kWh</label> during weekends and holidays, or during system issues.</td></tr></tbody></table> </div>';
                            }
                        }
                        else {
                            return '<div class="tooltip-container"><table class="c3-tooltip dailyTooltip"><tbody><tr class=""><th colspan="2">' + dailyDate + '</th></tr><tr><td class="name">Your total usage ' + usageText.toLowerCase() + ' hours for the day was <b class="value">' + d[i].value + 'kWh</b></td></tr></tbody></table></div>';
                        }
                    }
                }

            }
        },
        legend: {
            show: false
        }
    });

    if (mobiledailyvalues != null || mobiledailyvalues != {}) {

        var div = document.createElement('div');
        div.setAttribute("id", "tbl-daily");
        document.body.appendChild(div);

        var existingtable = document.getElementById("dailytable")

        if (existingtable) {
            document.getElementById("tbl-daily").removeChild(existingtable)
        }
        document.getElementById("tbl-daily").appendChild(buildTable(mobiledailyvalues));

        function buildTable(data) {
            var dailyusageType = data.usage[0];
            var table = document.createElement("table");
            table.setAttribute("class", "gridtable");
            table.setAttribute("id", "dailytable");
            var thead = document.createElement("thead");
            var tbody = document.createElement("tbody");
            var headRow = document.createElement("tr");
            if (dailyusageType === "Peak") {
                ["Date", "Usage During Peak Hours (kWh)"].forEach(function (el) {
                    var th = document.createElement("th");
                    th.setAttribute("scope", "col");
                    th.appendChild(document.createTextNode(el));
                    headRow.appendChild(th);
                });
            }
            else if (dailyusageType === "OffPeak") {
                ["Date", "Usage During Off-Peak Hours (kWh)"].forEach(function (el) {
                    var th = document.createElement("th");
                    th.setAttribute("scope", "col");
                    th.appendChild(document.createTextNode(el));
                    headRow.appendChild(th);
                });
            }

            thead.appendChild(headRow);
            table.appendChild(thead);

            var days = data.x;
            var usage = data.usage;

            for (var i = days.length - 1; i > 0; i--) {

                var formattedDate = moment.parseZone(days[i], moment.ISO_8601).format("MMM DD,YYYY");
                var tr = document.createElement("tr");
                var td = document.createElement("td");
                td.setAttribute("scope", "row");
                td.appendChild(document.createTextNode(formattedDate))
                tr.appendChild(td);
                var td1 = document.createElement("td");
                td1.setAttribute("scope", "row");
                td1.appendChild(document.createTextNode(usage[i]))
                tr.appendChild(td1);
                tbody.appendChild(tr);
            }
            table.appendChild(tbody);
            return table;
        }

    }
}

function GenerateMonthlyWebGraph(webmonthlyvalues, widthValue) {

    var dataArray = [webmonthlyvalues.x, webmonthlyvalues.Peak, webmonthlyvalues.OffPeak];  


   c3.generate({
        bindto: '#chart-monthly',

        size: {
            width: widthValue,

        },
        data: {
            x: 'x',
            // xFormat: '%Y-%m-%dT%H:%M:%S.%L%L%L%Z',
            columns: dataArray,
            type: 'bar',
            selection: { enabled: false }

        },
        color: {
            pattern: ['#069bd7', '#023A9A']
        },
        axis: {
            x: {

                padding: {
                    left: 1
                },
                //type: 'timeseries',
                //tick: {
                //    outer: false,
                //    fit: true,
                //    culling: false,
                //    format: '%b %d'

                //    // function(x) { return x.getMonth(); }
                //}

                type: 'category',
                tick: {
                    format: function (x) {
                        return moment.parseZone(webmonthlyvalues.x[x + 1], moment.ISO_8601).format("MMM DD");
                    }

                    // format: '%e-%b-%Y %H:%M'
                }
            },
            y: {
               
                inner: true,
                padding: {

                    top: 50
                },
                center: 0,
                max: parseFloat(webmonthlyvalues.y[webmonthlyvalues.y.length - 1]),
                tick: {
                    format: function (d) { return (d) + " kWh"; },
                    outer: false,
                    values: webmonthlyvalues.y
                }
            }
        },
        grid: {
            lines: {
                front: false
            },
            y: {
                show: true

            }

            // x: {
            //     lines: lines
            //}
        },
        bar: {

            width: 20 // this makes bar width 100px
        },
        tooltip: {
            contents: function (d, color) {
                if (d.length > 0) {
                    var s = webmonthlyvalues.xMetadata;


                    var title = moment.parseZone(s[d[0].index], moment.ISO_8601).format("MMM DD,YYYY") + " - " + moment.parseZone(webmonthlyvalues.x[d[0].x + 1], moment.ISO_8601).format("MMM DD,YYYY") ;
                    //return moment(webmonthlyvalues.x[x + 1], "YYYY-MM-DD").format("DD MMM");

                    //var title;
                    //for (var i = 0; i < s.length; i++) {
                    //    if (i == s.length - d[0].index - 1) {
                    //        var startDate = new Date(s[i]);
                    //        title = startDate.toLocaleDateString("en-US", options) + " - " + d[0].x.toLocaleDateString("en-US", options);
                    //    }
                    //}
                    var customTooltip = '<div class="tooltip-container"><table class="c3-tooltip"><tbody><tr class=""><th colspan="2">' + title + '</th></tr>'
                    var zerousage = true;
                    for (var i = 0; i < d.length; i++) {
                        if (d[i].value != 0) { zerousage = false;}
                    }
                    if (zerousage == true) return "";
                    for (var j = 0; j < d.length; j++) {
                        var content = d[j].id;
                        if (content === 'Peak') {

                            content = 'Usage During Peak Hours (kWh)';
                            customTooltip += '<tr><td><table class="innerContent"><tr><td style="width:2%"><span style ="background-color:#069bd7"></span></td><td style="width:90%;" class="name">' + content + '</td> <td style="width:10%" class="value">' + d[j].value + '</td></tr></table></td></tr>';

                        } else {
                            content = 'Usage During Off-Peak Hours (kWh)';
                            customTooltip += '<tr><td><table class="innerContent"><tr><td style="width:2%"><span style ="background-color:#023A9A"></span></td><td style="width:90%;" class="name">' + content + '</td> <td style="width:10%" class="value">' + d[j].value + '</td></tr></table></td></tr>';

                        }
                       
                    }
                    customTooltip += '</tbody ></table ></div >';
                    return customTooltip;
                }

            }
        },
        legend: {
            show: false
        }
     });

    if (dataArray != null || dataArray != {}) {

        var div = document.createElement('div');
        div.setAttribute("id", "tbl");
        div.setAttribute("class", "center-table");
        document.body.appendChild(div);

        var existingtable = document.getElementById("monthlytable")

        if (existingtable) {
            document.getElementById("tbl").removeChild(existingtable)
        }
        document.getElementById("tbl").appendChild(buildTable(dataArray));

        function buildTable(data) {

            var table = document.createElement("table");
            table.setAttribute("class", "gridtable");
            table.setAttribute("id", "monthlytable");
            var thead = document.createElement("thead");
            var tbody = document.createElement("tbody");
            var headRow = document.createElement("tr");
            ["Billing Cycle", "Usage During Peak Hours (kWh)", "Usage During Off-Peak Hours (kWh)"].forEach(function (el) {
                var th = document.createElement("th");
                th.setAttribute("scope", "col");
                th.appendChild(document.createTextNode(el));
                headRow.appendChild(th);
            });
            thead.appendChild(headRow);
            table.appendChild(thead);

            var arrayLength = data[0].length;

            for (var i = 1; i < arrayLength; i++) {

                var date = webmonthlyvalues.xMetadata;
                var title = moment.parseZone(date[i - 1], moment.ISO_8601).format("MMM DD,YYYY") + " - " + moment.parseZone(webmonthlyvalues.x[i], moment.ISO_8601).format("MMM DD,YYYY");

                var tr = document.createElement("tr");
                var td = document.createElement("td");
                td.setAttribute("scope", "row");
                td.appendChild(document.createTextNode(title))
                tr.appendChild(td);
                var td1 = document.createElement("td");
                td1.setAttribute("scope", "row");
                td1.appendChild(document.createTextNode(data[1][i]))
                tr.appendChild(td1);
                var td2 = document.createElement("td");
                td2.setAttribute("scope", "row");
                td2.appendChild(document.createTextNode(data[2][i]))

                tr.appendChild(td2);
                tbody.appendChild(tr);
            }
            table.appendChild(tbody);
            return table;
        }


    }

}



    
  

function GenerateMonthlyMobileGraph(mobilemonthlyvalues) {

   
    var dataArray = [mobilemonthlyvalues.x, mobilemonthlyvalues.Peak];
    if (mobilemonthlyvalues.OffPeak != undefined) {
        dataArray.push(mobilemonthlyvalues.OffPeak);
    }
   
      c3.generate({
        bindto: '#chart-monthly-mobile',
        padding: {
            top: 10,
            bottom: 10
        },
        data: {
            x: 'x',
            xFormat: '%Y-%m-%dT%H:%M:%S.%L%L%L%Z',
            columns: dataArray,
            type: 'bar'
        },
        color: {
            pattern: ['#069bd7', '#023A9A']
        },
        axis: {
            x: {
                //type: 'timeseries',
                //fit: true,
                //centered: true,
                //tick: {
                //    outer: false,
                //    count: 3,
                //    fit: true,
                //    format: '%b %d',
                //   // function(x) { return x.getMonth(); }
                //},
                padding: {
                    left: 1

                },

                 type: 'category',
                tick: {
                    format: function (x) {
                        return moment.parseZone(mobilemonthlyvalues.x[x + 1], moment.ISO_8601).format("MMM DD");

                     }

                    // format: '%e-%b-%Y %H:%M'
                }
            },
            y: {
                padding: { top: 50 },
                inner: true,
                center: 0,
                max: parseFloat(mobilemonthlyvalues.y[mobilemonthlyvalues.y.length - 1]),
                tick: {
                    format: function (d) { return d + " kWh"; },
                    outer: false,
                   
                    values: mobilemonthlyvalues.y
                }
            }
        },
        grid: {
            lines: {
                front: false
            },
            y: {
                show: true
            }
            //,
            //x: {
            //    lines: lines
            //}
        },
        bar: {
            
            width: 20 // this makes bar width 100px
        },
        tooltip: {
            
            contents: function (d, color) {
                if (d.length > 0) {
                    var s = mobilemonthlyvalues.xMetadata;
                    var title = moment.parseZone(s[d[0].index], moment.ISO_8601).format("MMM DD,YYYY") + " - " + moment.parseZone(mobilemonthlyvalues.x[d[0].x + 1], moment.ISO_8601).format("MMM DD,YYYY");

                    //var title;
                    //for (var i = 0; i < s.length; i++) {
                    //    if (i == s.length - d[0].index - 1) {
                    //        var startDate = new Date(s[i]);
                    //        title = startDate.toLocaleDateString("en-US", options) + " - " + d[0].x.toLocaleDateString("en-US", options);
                    //    }
                    //}

                    var zerousage = true;
                    for (var i = 0; i < d.length; i++) {
                        if (d[i].value != 0) { zerousage = false; }
                    }
                    if (zerousage == true) return "";

                   // var mobileDate = d[0].x.toLocaleDateString("en-US", options)
                    var customTooltip = '<div class="tooltip-container"><table class="c3-tooltip"><tbody><tr class=""><th colspan="2">' + title + '</th></tr>'
                    for (var j = 0; j < d.length; j++) {
                        var content = d[j].id;
                        if (content === 'Peak') {
                            content = 'Usage During Peak Hours (kWh)';
                            customTooltip += '<tr><td><table class="innerContent"><tr><td style="width:2%"><span style ="background-color:#069bd7"></span></td><td style="width:90%;" class="name">' + content + '</td> <td style="width:10%" class="value">' + d[j].value + '</td></tr></table></td></tr>';

                        } else {
                            content = 'Usage During Off-Peak Hours (kWh)';
                            customTooltip += '<tr><td><table class="innerContent"><tr><td style="width:2%"><span style ="background-color:#023A9A"></span></td><td style="width:90%;" class="name">' + content + '</td> <td style="width:10%" class="value">' + d[j].value + '</td></tr></table></td></tr>';

                        }
                    }
                    customTooltip += '</tbody ></table ></div >';
                    return customTooltip
                }

            }
        },
        legend: {
            show: false
        }
      });

    if (dataArray != null || dataArray != {}) {

        var div = document.createElement('div');
        div.setAttribute("id", "tbl");
        document.body.appendChild(div);

        var existingtable = document.getElementById("monthlytable")

        if (existingtable) {
            document.getElementById("tbl").removeChild(existingtable)
        }
        document.getElementById("tbl").appendChild(buildTable(dataArray));

        function buildTable(data) {

            var table = document.createElement("table");
            table.setAttribute("class", "gridtable");
            table.setAttribute("id", "monthlytable");
            var thead = document.createElement("thead");
            var tbody = document.createElement("tbody");
            var headRow = document.createElement("tr");
            ["Billing Cycle", "Usage During Peak Hours (kWh)", "Usage During Off-Peak Hours (kWh)"].forEach(function (el) {
                var th = document.createElement("th");
                th.setAttribute("scope", "col");
                th.appendChild(document.createTextNode(el));
                headRow.appendChild(th);
            });
            thead.appendChild(headRow);
            table.appendChild(thead);

            var arrayLength = data[0].length;

            for (var i = 1; i < arrayLength; i++) {

                var date = mobilemonthlyvalues.xMetadata;
                var title = moment.parseZone(date[i - 1], moment.ISO_8601).format("MMM DD,YYYY") + " - " + moment.parseZone(mobilemonthlyvalues.x[i], moment.ISO_8601).format("MMM DD,YYYY");

                var tr = document.createElement("tr");
                var td = document.createElement("td");
                td.setAttribute("scope", "row");
                td.appendChild(document.createTextNode(title))
                tr.appendChild(td);
                var td1 = document.createElement("td");
                td1.setAttribute("scope", "row");
                td1.appendChild(document.createTextNode(data[1][i]))
                tr.appendChild(td1);
                var td2 = document.createElement("td");
                td2.setAttribute("scope", "row");
                td2.appendChild(document.createTextNode(data[2][i]))

                tr.appendChild(td2);
                tbody.appendChild(tr);
            }
            table.appendChild(tbody);
            return table;
        }

    }
}
}());

if (typeof (module) !== 'undefined') {
    module.exports = window.UsageGraph;
}
else if (typeof define === 'function' && define.amd) {
    define([], function () {
        'use strict';
        return window.UsageGraph;
    });
};
