/* These are the date objects to track the date */
var todayDate = new Date ();
var stopDate = new Date ("April 17, 2009");
var twoLineStopDate = new Date ("August 19, 2009");
var dailyDate = new Date ();
var weeklyChart = 0;
var weeklyChartCount = 12;

/* Button visible values */
var btnDayNextVisible = false;
var btnDayPreviousVisible = true;
var btnWeekNextVisible = false;
var btnWeekPreviousVisible = true;

/* Current chart type being updated */
var currChartUpdating = '';

/* If we are using the 2 line daily chart */
var using2Line = false;

/* Keep track of the timeouts */
var dayTimeout = null;
var weekTimeout = null;

/**
 * Update the daily or weekly chart
 * This will set itself up to run again in 5 minutes for the daily chart and
 * 60 minutes for the weekly chart
*/
function updateChart (prefix, chart) {
    // Determine the url we need
    var url = '';
    if (chart == 'DAILY') {
        var c = 'DAILY';
        if (using2Line) {
            c = 'DAILY2LINE';
        }
        
        url = prefix +
              "/data/getChartData.php?siteIdName=" +
              siteIdName +
              "&chartType=" + c + "&chartDay=" +
              formatDate (dailyDate.getFullYear (),
                          dailyDate.getMonth (),
                          dailyDate.getDate ());
    }
    else if (chart == 'WEEKLY') {
        url = prefix +
              "/data/getChartData.php?siteIdName=" +
              siteIdName +
              "&chartType=WEEKLY&chartNumber=" +
              weeklyChart;
    }
    
    // Set up the request
    new Ajax.Request (url,
                      {
                        method: 'post',
                        onComplete: function (transport) {
                            if (currChartUpdating == 'DAILY') {
                                //$('dailyLoading').hide ();
                                //$('dailyChart').show ();
                                currChartUpdating = '';
                            }
                            else if (currChartUpdating == 'WEEKLY') {
                                //$('weeklyLoading').hide ();
                                //$('weeklyChart').show ();
                                currChartUpdating = '';
                            }
                            
                            if (chart == 'DAILY') {
                                //Effect.Appear ($('dailyChart'));
                                updateChartXML ('swfDailyChart', transport.responseText);
                                //$('dailyLoading').hide ();
                                
                                if (dailyDate.getMonth () == todayDate.getMonth () &&
                                    dailyDate.getDate () == todayDate.getDate ()) {
                                    // We only need to update the chart if it's today's chart
                                    dayTimeout = setTimeout ("updateChart ('" + prefix + "', 'DAILY')", 300000);  // Wait 5 more minutes and do again
                                }
                            }
                            else if (chart == 'WEEKLY') {
                                updateChartXML ('swfWeeklyChart', transport.responseText);
                                
                                if (weeklyDate.getMonth () >= todayDate.getMonth () &&
                                    weeklyDate.getDate () >= todayDate.getDate ()) {
                                    // We only need to update the chart if it's this week's chart
                                    weekTimeout = setTimeout ("updateChart ('" + prefix + "', 'WEEKLY')", 3600000);  // Wait 1 hour and do again
                                }
                            }
                        }
                      });
}


/*
Update the current output o-meter
This sets itself up to run again in 20 seconds
*/
function updateCurrentOutput (prefix, site, elem) {
    var url = prefix + '/data/generateCurrentOutput.php';
    if (site != '') {
        url += '?siteIdName=' + site;
    }
    
    new Ajax.Request (url,
                      {
                        method: 'post',
                        onComplete: function (transport) {
                            $(elem).src = transport.responseText.split ('\n')[0];
                            setTimeout ("updateCurrentOutput ('" +
                                        prefix +
                                        "', '" +
                                        site +
                                        "', '" +
                                        elem +
                                        "')",
                                        45000);  // Run again in 45 seconds
                        }
                      });
}


/*
Change the timeframe of a day or week chart
*/
function changeChartTimeframe (prefix, type, goForward) {
    // Cancel the automatic update and set which chart we are updating
    if (type == 'DAILY') {
        clearTimeout (dayTimeout);
        currChartUpdating = 'DAILY';
    }
    else if (type == 'WEEKLY') {
        clearTimeout (weekTimeout);
        currChartUpdating = 'WEEKLY';
    }
    
    // Change the date timeframe
    if (type == 'DAILY') {
        if (goForward) {
            dailyDate.setDate (dailyDate.getDate () + 1);
        }
        else {
            dailyDate.setDate (dailyDate.getDate () - 1);
        }
    }
    else if (type == 'WEEKLY') {
        if (goForward) {
            weeklyChart -= 1;
        }
        else {
            weeklyChart += 1;
        }
    }
    
    // Check for buttons that need disabled
    if (type == 'DAILY') {
        // Are we changing the date to today?
        if (dailyDate.getMonth () == todayDate.getMonth () &&
            dailyDate.getDate () == todayDate.getDate ()) {
            if (btnDayNextVisible != false) {
                $('btnDayNext').hide ();
                btnDayNextVisible = false;
            }
        }
        else {
            if (btnDayNextVisible != true) {
                $('btnDayNext').show ();
                btnDayNextVisible = true;
            }
        }
        
        // Are we changing the date to the stop date?
        if (dailyDate.getMonth () == stopDate.getMonth () &&
            dailyDate.getDate () == stopDate.getDate ()) {
            if (btnDayPreviousVisible != false) {
                $('btnDayPrevious').hide ();
                btnDayPreviousVisible = false;
            }
        }
        else {
            if (btnDayPreviousVisible != true) {
                $('btnDayPrevious').show ();
                btnDayPreviousVisible = true;
            }
        }
        
        // Are we using 2 line and going to the 2 line stop date?
        if (dailyDate >= twoLineStopDate) {
            $('dvUse2Line').show ();
        }
        else {
            $('cbxUse2Line').checked = false;
            $('dvUse2Line').hide ();
            $('dvDailyConsumptionExplination').hide ();
            $('dvDailyRegularExplination').show ();
            using2Line = false;
        }
    }
    else if (type == 'WEEKLY') {
        // Are we changing the date to this week?
        if (weeklyChart == 0) {
            if (btnWeekNextVisible != false) {
                $('btnWeekNext').hide ();
                btnWeekNextVisible = false;
            }
        }
        else {
            if (btnWeekNextVisible != true) {
                $('btnWeekNext').show ();
                btnWeekNextVisible = true;
            }
        }
        
        // Are we changing the date to the stop week?
        if (weeklyChart == (weeklyChartCount -1)) {
            if (btnWeekPreviousVisible != false) {
                $('btnWeekPrevious').hide ();
                btnWeekPreviousVisible = false;
            }
        }
        else {
            if (btnWeekPreviousVisible != true) {
                $('btnWeekPrevious').show ();
                btnWeekPreviousVisible = true;
            }
        }
    }
    
    // Call update chart
    updateChart (prefix, type);
}


function resetChartChangeSetup () {
    // Reset day and button stuff
    dailyDate = new Date ();
    weeklyDate = new Date ();
    $('btnDayPrevious').show ();
    $('btnDayNext').hide ();
    $('btnWeekPrevious').show ();
    $('btnWeekNext').hide ();
    btnDayNextVisible = false;
    btnDayPreviousVisible = true;
    btnWeekNextVisible = false;
    btnWeekPreviousVisible = true;
    $('cbxUse2Line').checked = false;
}


function formatDate (year, month, day) {
    month = month + 1;
    return year + "-" + month + "-" + day;
}