function plotAccordingToChoices(opts) {
//   //console.log('re-plotting');
//   var data = [];
// 
//   if ($('#graph_options_checkboxes').find("input:checked").length == 0) {
//     $('#graph_options_notice').text('You must select at least one item to display');
//   } else {
//     $('#graph_options_notice').text('');
//   }
// 
//   $('#graph_options_checkboxes').find("input:checked").each(function () {
//       var key = $(this).attr("name");
//       //console.log("Drawing " + key);
//       if (key && main_data[key])
//       data.push(main_data[key]);
//       //console.log('pushing data for ' + key + ': ' + main_data[key] + ' (size: ' + main_data[key]['data']adius'] + ')');
//       });
// 
//   
//   if (data.length > 0)
//     var opts = { xaxis: { tickDecimals: 0}};
//     if (main_zoom_x1 != undefined) {
//       //console.log('using saved xaxis_zoom:  ' + main_zoom_x1);
//       opts['xaxis']['min'] = main_zoom_x1;
//       opts['xaxis']['max'] = main_zoom_x2;
//       //opts['xaxis'] = { min: main_zoom_x1, max: main_zoom: x2 };
//     } else {
//       //console.log('not using saved xasix_zoom');
//     }
// 
//     $.plot($("#graph_content"), data,
//         $.extend(true, {}, main_options, opts));
// //.          {
// //      yaxis: { min: 0 },
// //      xaxis: { tickDecimals: 0, min: main_zoom_x1, max: main_zoom_x2 }
// //    }));
// 
// //        $.extend(true, {}, main_options, {
// //      yaxis: { min: 0 },
// //      xaxis: { tickDecimals: 0 }
// //    }));
}

function updateGraphData(main, overview) {
  main_chart_data = main;
  overview_chart_data = overview;

  main_data = main_chart_data[0];
  main_options = main_chart_data[1];

  overview_data = overview_chart_data[0];
  overview_options = overview_chart_data[1];
}

function updateWeights(main, overview) {
  updateGraphData(main, overview);
  MYW.graphs.draw();
}

function initGraph(main_chart_data, overview_chart_data) {
  updateGraphData(main_chart_data, overview_chart_data);
  
  // hard-code color indices
  var i = 0;
  $.each(main_data, function(key, val) {
    val.color = i;
    ++i;
  });

  //main_options['grid'] = { coloredAreas: weekendAreas };

  plot = $.plot($('#graph_content'), main_data, main_options);
  overview = $.plot($('#graph_overview'), overview_data, overview_options);

  // now connect the two
  var internalSelection = false;

  $("#graph_content").bind("selected", function (event, area) {
    // do the zooming
    main_zoom_x1 = area.x1;
    main_zoom_x2 = area.x2;

    MYW.graphs.draw();
    //  plot = $.plot($("#graph_content"), main_data,
    //  $.extend(true, {}, main_options, {
      //    xaxis: { min: area.x1, max: area.x2 }
      //  }));

    if (internalSelection)
    return; // prevent eternal loop
    internalSelection = true;
    overview.setSelection(area);
    internalSelection = false;
  });

  $("#graph_overview").bind("selected", function (event, area) {
    if (internalSelection)
    return;
    internalSelection = true;
    plot.setSelection(area);
    internalSelection = false;
  });

  main_zoom_x1 = undefined;
  main_zoom_x2 = undefined;
    
  plotAccordingToChoices();
  MYW.graphs.draw();
}

function zoomTo(date1, date2) {
  overview.setSelection({x1: date1.getTime(), x2: date2.getTime()});
}

// helper for returning the weekends in a period
function weekendAreas(plotarea) {
  var areas = [];
  var d = new Date(plotarea.xmin);
  // go to the first Saturday
  d.setDate(d.getDate() - ((d.getDay() + 1) % 7))
    d.setSeconds(0);
  d.setMinutes(0);
  d.setHours(0);
  var i = d.getTime();
  do {
    // when we don't set y1 and y2 the rectangle
    // automatically extends to infinity in those directions
    areas.push({ x1: i, x2: i + 2 * 24 * 60 * 60 * 1000 });
    i += 7 * 24 * 60 * 60 * 1000;
  } while (i < plotarea.xmax);

  return areas;
}


function fillValue(elem, def) {
  if (elem.value == "") {
    elem.value = def;
  }
}

function clearValue(elem, def) {
  if (elem.value == def) {
    elem.value = "";
  }
}

function initWeightMonthsDropdown(json) {
  initDates();
  weight_months = json;
  // resetWeightMonthsDropdown(new Date);

}

function resetWeightMonthsDropdown(selected) {
  var options = '';

  if (selected != null) {
    selected_month = selected.getMonth() + 1;
    selected_year = selected.getFullYear();
  } else {
    selected_year = selected_month = 0;
  }

  //for (var i = 0; i < weight_months.length; i++) {
  for (var year in weight_months) {
      options += '<optgroup label="' + year + '">';

      //for (var i = 0; i < weight_months[year].length; i++) {
      for (var month in weight_months[year]) {
        if (weight_months[year][month] != null) {
          //d = new Date(weight_months[year][i][0]);
          //month = weight_months[year][i][0];
          //y = new String(d.getFullYear()).substring(2);
          y = year.substring(2);
          str = month_names[month];
          //str += " '" + y + ' (' + weight_months[year][i][1] + ')';
          str += " '" + y + ' (' + weight_months[year][month][0] + ')';

          options += '<option '
          if (year == selected_year && month == selected_month) {
            options += 'selected="true" '
          }
          options += 'value="' + weight_months[year][month][1] + '">' + str + '</option>';
        }
      }

      options += '<\optgroup>';
  }
  $('#month_for_weight_list').html(options);
}

function ensureWeightMonthsHasDate(d) {
  year = d.getFullYear();
  month = d.getMonth() + 1;
  if (weight_months[year] == undefined)
    weight_months[year] = [];
  if (weight_months[year][month] == undefined)
    weight_months[year][month] = [0,d];
}

function decrementWeightCount(d) {
  ensureWeightMonthsHasDate(d);
  year = d.getFullYear();
  month = d.getMonth() + 1;
  weight_months[year][month][0] -= 1;
}

function incrementWeightCount(d) {
  ensureWeightMonthsHasDate(d);
  year = d.getFullYear();
  month = d.getMonth() + 1;
  weight_months[year][month][0] += 1;
}

function initDates() {
  month_names = ["", "Jan", "Feb", "Mar", 
              "Apr", "May", "Jun",
              "Jul", "Aug", "Sep",
              "Oct", "Nov", "Dec"]

  day_names = new Array ( );
  day_names[day_names.length] = "Sunday";
  day_names[day_names.length] = "Monday";
  day_names[day_names.length] = "Tuesday";
  day_names[day_names.length] = "Wednesday";
  day_names[day_names.length] = "Thursday";
  day_names[day_names.length] = "Friday";
  day_names[day_names.length] = "Saturday";
}

function initPage(earliest) {
  earliest_date = earliest;
  datepicker_inited = false;
  $('#menu').bind('tabsshow', function(event, ui) {
      if (ui.panel.id == "graph_options" && datepicker_inited != true) {
        initGraphOptionsTab();
        datepicker_inited = true;
      }
    });
}

function initGraphOptionsTab() {
  //$('#date_range_picker').daterangepicker();
  $('#date_range_picker').daterangepicker({
    earliestDate: earliest_date,
    latestDate: Date.parse('today'),
    presetRanges: [
      {text: 'Last 30 days', dateStart: 'Today-30', dateEnd: 'Today' },
      {text: 'Year to date', dateStart: function(){ var x= Date.parse('today'); x.setMonth(0); x.setDate(1); return x; }, dateEnd: 'today' },
      {text: 'All dates', dateStart: function() {return earliest_date}, dateEnd: 'today' }
    ]
  })
}
