//<![CDATA[
// Read in and display user data
$.ajax({
  url: 'user.json',
  dataType: 'json',
  success: function(jsonData, msg) {
      $('#userInfo').append(jsonData.username);
      $('#userInfo').append(' (' + jsonData.firstname + ' ' + jsonData.lastname);
      $('#userInfo').append(', User id: ' + jsonData.userid + ')');
  },
  error: function(oXHR, textStatus) {
      alert('Error in user.json: ' + textStatus);
  }
});

// Read in and display accounts data
$.ajax({
  //url: 'account.json', // original file
  url: 'accounts.json', // modified file: multiple accounts, premises & meters
  dataType: 'json',
  success: function(oAccountInfo, msg) {
      var eParentNode = document.getElementById('accountInfo');
      displayObject(oAccountInfo, eParentNode);
      // Hide all but the starting values (0th elts of the arrays)
      for (var i in aMultiples) {
        for (var j=1; j<aMultiples[i].length; j++) {
          var id = aMultiples[i][j];
          $('#'+id).hide();
        }
      }
  },
  error: function(oXHR, textStatus) {
      alert('Error in account.json: ' + textStatus);
  }
});

// Read in and display usage data
$.ajax({
  url: 'intervals.json',
  dataType: 'json',
  success: function (oUsageInfo) {
      chartUsageData(oUsageInfo);
      $('#costPlot').hide(); // Hide cost plot initially
      $('#carbonPlot').hide(); // Hide carbon plot initially
      $('#buttonResetZoom').click(function(){
          plotPower.resetZoom();
        });
  },
  error: function(oXHR, textStatus) {
      alert('Error in intervals.json: ' + textStatus);
  }
});

// Init stuff to do on page ready
$(document).ready(function(){
    $('#usageText').hide(); // Hide text data table initially

    // Attach event listener/handler for <<PREVIOUS and NEXT>> button clicks
    // Catches all button clicks within #accountInfo div, so can use just one
    //  event handler for all the buttons in that section (This works since
    //  any click event in this section will bubble up to the parent div)
    $('#accountInfo').click(function(e){
        if ( e.target.nodeName == 'BUTTON' ){ // a button was clicked
            if ( /navPrev/.test(e.target.className) ){ // prev button click
                var elt, prevElt, nextElt, id, prevId, nextId, k = 0;
                var idStem = e.target.id.replace(/button_prev_/, '');
                do { // get current and next one until find visible or last one
                  id = idStem + '_' + k++;
                  elt = document.getElementById(id);
                  nextId = idStem + '_' + k;
                  nextElt = document.getElementById(nextId);
                } while ( (elt.style.display == 'none') && (nextElt) );
                prevId = idStem + '_' + (k-2);
                prevElt = document.getElementById(prevId);
                if (prevElt) { // we're not on first one
                  elt.style.display = 'none'; // make invisible
                  prevElt.style.display = ''; // make visible
                  // TODO: Swap data in usage section (when have data :)
                }
            } else { // next button click
                var elt, nextElt, id, nextId, k = 0;
                var idStem = e.target.id.replace(/button_next_/, '');
                do { // get current and next one until find visible or last one
                  id = idStem + '_' + k++;
                  elt = document.getElementById(id);
                  nextId = idStem + '_' + k;
                  nextElt = document.getElementById(nextId);
                } while ( (elt.style.display == 'none') && (nextElt) );
                if (nextElt) { // we're not on last one
                  elt.style.display = 'none'; // make invisible
                  nextElt.style.display = ''; // make visible
                  // TODO: Swap data in usage section (when have data :)
                }
            }
        }
    });

    // SexyLightbox init
    //if (!/android|iphone|ipod|ipad|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
    if ( ! isMobileBrowser() ) { // helperFcns.js::isMobileBrowser()
        SexyLightbox.initialize({ // Init pop-up fcns
          color: 'black',
          moveDuration: 100,
          dir: 'js/sexy-lightbox/sexyimages/',
          imagesdir: 'js/sexy-lightbox/sexyimages/'
        });

        $('#buttonInfo').click(function(){ // Event handler for Info button
            SexyLightbox.display("alert.html?height=580&width=700");
        });
    } else { // Dont use sexylightbox for mobile devices
        $('#buttonInfo').click(function(){ // Event handler for Info button
            window.location='alert.html';
        });
    }

    // Start with graphical data display showing and textual data hidden
    // Give UI options to switch between the two

    // "Show Data Graphically" button handler
    $("#buttonDisplayGraphic").click(function(){
        $("#usageText").fadeOut('slow');
        $("#usageChart").fadeIn();
        $("#buttonDisplayGraphic").hide();
        $("#buttonDisplayText").show();
        $("#displayDropDown").show();
        $("#resetZoom").show();
      });
    // "Show Data as Text" button handler
    $("#buttonDisplayText").click(function(){
        $("#usageChart").fadeOut();
        $("#usageText").fadeIn('slow');
        $("#buttonDisplayText").hide();
        $("#buttonDisplayGraphic").show();
        $("#displayDropDown").hide();
        $("#resetZoom").hide();
      });

    // Select drop-down handler & corresponding "Reset Zoom" button handlers
    $("#selectPlotDropDown").change(function(){
        switch ( $(this).val() ) {
          case 'power' : {
            $('#carbonPlot').hide();
            $('#costPlot').hide();
            $('#powerPlot').show();
            $('#buttonResetZoom').unbind('click');
            $('#buttonResetZoom').click(function(){
                plotPower.resetZoom();
            });
            break;
          }
          case 'carbon' : {
            $('#costPlot').hide();
            $('#powerPlot').hide();
            $('#carbonPlot').show();
            $('#buttonResetZoom').unbind('click');
            $('#buttonResetZoom').click(function(){
                plotCarbon.resetZoom();
            });
            break;
          }
          case 'cost' : {
            $('#powerPlot').hide();
            $('#carbonPlot').hide();
            $('#costPlot').show();
            $('#buttonResetZoom').unbind('click');
            $('#buttonResetZoom').click(function(){
                plotCost.resetZoom();
            });
            break;
          }
          default : { // default to Power Usage Plot
            $('#carbonPlot').fadeOut();
            $('#costPlot').fadeOut();
            $('#powerPlot').fadeIn();
            $('#buttonResetZoom').unbind('click');
            $('#buttonResetZoom').click(function(){
                plotPower.resetZoom();
            });
          }
        }
      });

});
//]]>

