//<![CDATA[
// Info from the HTML markup
var usageTextId = 'usageText'; // Container for text data table
var powerPlotId = 'powerPlot', costPlotId = 'costPlot', carbonPlotId = 'carbonPlot';

// Hardcoded values that would be likely extracted from data stream or a DB in a real app
var granularity = 'DAY';
var aCostPerKwhByTier = new Array('.050', '.065', '.075');
var carbonCoefficient = 12.89;
var aUsageTableHeadings = new Array('Date', 'Usage (kWh)', 'Usage Category', 'Cost', 'Carbon Emitted');

// Arrays to hold data for different graphing options ( accessed by chartUsageData() )
var aUsagePlotData = Array(), aCostPlotData = Array(), aCarbonPlotData = Array();


// Function to calculate 'Cost' and 'Carbon Emitted', and add as columns to aUsageData[]
//
// NOTE: Original array <aUsageData> is modified (arrays/objects are passed by reference :)
// Also populates aUsagePlotData[], aCostPlotData[] and aCarbonPlotData[] arrays for graphing
// RETURNS: nada
function addCostAndCarbonCols(aUsageData) {
  var NUMCOLS = aUsageTableHeadings.length; // Note: only handles data arrays w/constant # of cols
  var DATECOL = 0, USAGECOL = 1, TIERCOL = 2; // these need to stay synced with the usage data format
  var tier, powerUsage;

  for (var interval in aUsageData) {
    tier = aUsageData[interval][TIERCOL].match(/\d+/); // extract digit representing tier category
    sCost = aCostPerKwhByTier[tier-1]; // Tier1 maps to aCostPerKwhByTier[0], etc.
    costPerKwh = parseFloat( sCost );

    aUsageData[interval][TIERCOL] += ' ($'+sCost+'/kWh)'; // annotate billing tier with actual price/kWh
    powerUsage = parseFloat(aUsageData[interval][USAGECOL]);
    // Populate separate array to graph power usage
    // NOTE: This separate array is not strictly necessary (could just use aUsageData[]),
    //        but is done for clarity (could remove for speed)
    aUsagePlotData.push( [ aUsageData[interval][DATECOL], powerUsage ] );

    // Calculate cost and update data structures accordingly
    cost = powerUsage * costPerKwh;
    cost = dollarCentsFormat(cost);
    aUsageData[interval][NUMCOLS-2] = '$' + cost; // Append column to aUsageData[]
    // Populate separate array to graph cost
    aCostPlotData.push( [ aUsageData[interval][DATECOL], parseFloat(cost) ] );
    
    // Calculate carbonUsage and update data structures accordingly
    carbonUsage = powerUsage * carbonCoefficient;
    carbonUsage = dollarCentsFormat(carbonUsage);
    aUsageData[interval][NUMCOLS-1] = carbonUsage + ' lbs'; // Append column to aUsageData[]
    // Populate separate array to graph carbonUsage
    aCarbonPlotData.push( [ aUsageData[interval][DATECOL], parseFloat(carbonUsage) ] );
  }
}


// Function to create middle/premise section of UI
//
var aMultiples = new Array(); // Array to hold id's of multiple items
// Recursively parse object oObj and create/insert tree of HTML DOM elements at eParentNode
// CALLS: helperFcns.js::typeOf(), helperFcns.js::HtmlElement()
// RETURNS: nada
function displayObject(oObj, eParentNode) {
  var id, value, valueType, objType, eNewDiv, eNewElt, eNewBr;

  for (prop in oObj) {
    value = oObj[prop];
    valueType = typeOf(value);
    objType = typeOf(oObj);
    // Store the hierarchy in the id for future reference
    id = eParentNode.getAttribute('id') + '_' + prop;

    if ( value && typeof value === 'object') { // New container div for embedded objects
      eNewDiv = new HtmlElement('div', eParentNode, id);

      // Populate aMultiples[] for embedded arrays (ie, multiples accounts, premises, etc)
      if (objType === 'array') {
        if (aMultiples[eParentNode.id] === undefined) {
          aMultiples[eParentNode.id] = new Array();
        }
        aMultiples[eParentNode.id][prop] = id;
      } else {
        eNewElt = new HtmlElement('h2', eNewDiv.elt, null, prop.toUpperCase());
      }

      eParentNode = eNewDiv.elt; // Container div becomes parent node for the new object

      // Put each multiple element in its own column
      if ( valueType === 'array') {
        eNewDiv.elt.className = 'colAlign';
        if (prop.match(/accounts/) == null) {
          eNewDiv.elt.className += ' shiftRight';
        }
        // Create prev/next buttons to cycle through multiple elements
        eNewElt = new HtmlElement('button', eNewDiv.elt, 'button_prev_'+id, '<< Previous');
        eNewElt.elt.className = 'button navPrev';
        eNewElt = new HtmlElement('button', eNewDiv.elt, 'button_next_'+id, 'Next >>');
        eNewElt.elt.className = 'button';
      }

      eParentNode = displayObject(value, eParentNode);
    } else if ( (value !== undefined) && (value !== null) ) {
      // Display leaf nodes as <span>'s separated by <br>'s
      eNewElt = new HtmlElement('span', eParentNode, id, prop+': '+value);
      eNewBr = document.createElement('br');
      eNewElt.elt.appendChild(eNewBr);
    }
  } // for

  return eParentNode.parentNode;
}


// Function to create bottom section of UI
//
// Create textual and graphical representations of oUsageInfo data
// CALLS: helperFcns.js::HTMLtable(), displayFcns.js::addCostAndCarbonCols()
// RETURNS: nada
function chartUsageData(oUsageInfo) {

  // Create textual version of usage section, via putting aUsageInfo in an html table
  //
  var aUsageInfo = oUsageInfo.rateplan.granularities[granularity].intervals;
  addCostAndCarbonCols(aUsageInfo);
  var eTableParent = document.getElementById(usageTextId);
  var oUsageTable = new HtmlTable(aUsageTableHeadings, aUsageInfo, eTableParent);

  // Create graphical plots with the aUsageInfo, aCost, and aCarbonUsage data
  //
  // Calculate space between vertical grid lines on graph
  //var tickWidth = oUsageTable.numRows / 8.42; // use for 4-digit yrs
  var tickWidth = oUsageTable.numRows / 10; // use for 2-digit yrs
  var sMinDate = 'January 1, 2009'; // would be generated from first interval in real app

  var sTitleLabel = 'Power Usage in kWh';
  plotPower = $.jqplot(powerPlotId, [aUsagePlotData], {
    title: sTitleLabel,
    series: [{
        label: sTitleLabel,
        neighborThreshold: -1
            }],
    axes: {
      xaxis: {
        renderer:$.jqplot.DateAxisRenderer,
            min: sMinDate,
            tickInterval: tickWidth + ' ' + granularity.toLowerCase(),
            tickOptions:{formatString:'%#m/%#d/%y'}
      },
      yaxis: {
        renderer: $.jqplot.LogAxisRenderer,
            tickOptions:{formatString:'%.4f'}
      }
    },
    cursor:{zoom:true, showTooltip:true}
  });

  sTitleLabel = 'Carbon Emitted to Atmosphere in Pounds (lbs)';
  plotCarbon = $.jqplot(carbonPlotId, [aCarbonPlotData], {
    title: sTitleLabel, 
    series: [{
        label: sTitleLabel,
        neighborThreshold: -1
            }],
    axes: {
      xaxis: {
        renderer:$.jqplot.DateAxisRenderer,
            min: sMinDate,
            tickInterval: tickWidth + ' ' + granularity.toLowerCase(),
            tickOptions:{formatString:'%#m/%#d/%y'}
      },
      yaxis: {
        renderer: $.jqplot.LogAxisRenderer,
            tickOptions:{formatString:'%.4f'}
      }
    },
    cursor:{zoom:true, showTooltip:true}
  });

  sTitleLabel = 'Cost in Dollars ($)';
  plotCost = $.jqplot(costPlotId, [aCostPlotData], {
    title: sTitleLabel,
    series: [{
        label: sTitleLabel,
        neighborThreshold: -1
            }],
    axes: {
      xaxis: {
        renderer:$.jqplot.DateAxisRenderer,
            min: sMinDate,
            tickInterval: tickWidth + ' ' + granularity.toLowerCase(),
            tickOptions:{formatString:'%#m/%#d/%y'}
      },
      yaxis: {
        renderer: $.jqplot.LogAxisRenderer,
            tickOptions:{formatString:'%.2f'}
      }
    },
    cursor:{zoom:true, showTooltip:true}
  });
}
//]]>

