if (typeof(MYW) == 'undefined') {
  MYW = {};
}

MYW.initPage = function(weightCollection) {
  MYW.weights = weightCollection;
  MYW.weightMonthsDropdown.update();
  MYW.graphs.initOptions();
};


if (typeof(MYW) == 'undefined')
  MYW = {};

MYW.graphs = {
  draw: function() {
    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");
      if (key && main_data[key])
        data.push(main_data[key]);
    });

    if (data.length > 0)
      var opts = { xaxis: { tickDecimals: 0}};

    if (main_zoom_x1 != undefined) {
      opts['xaxis']['min'] = main_zoom_x1;
      opts['xaxis']['max'] = main_zoom_x2;
    }

    $.plot($("#graph_content"), data,
           $.extend(true, {}, main_options, opts));
  },

  initOptions: function() {
    if( document.getElementById &&
       document.getElementsByTagName ){
      if( document.getElementById( 'graph_options_checkboxes' ) ){
        var container = document.getElementById( 'graph_options_checkboxes' );
        var options = container.getElementsByTagName( 'input' );

        for (var i = 0; i < options.length; i++ ) {
          options[i].onclick = function(){
            return MYW.graphs.draw();
          };
        }
      }
    }
  }
}


if (typeof(MYW) == 'undefined') {
  MYW = {};
}

MYW.weightCollection = {
  year: function(jsYear) {
    var that = {
      jsYear: jsYear,
      name: jsYear + 1900,
      months: [],
      shortName: String(jsYear).substring(1)
    };

    that.addRecord = function(weightRecord) {
      that.months[weightRecord.date.getMonth()] = that.months[weightRecord.date.getMonth()] || MYW.weightCollection.month(weightRecord.date.getMonth());
      that.months[weightRecord.date.getMonth()].addRecord(weightRecord);
    };

    return that;
  },

  month: function(jsMonthIndex) {
    var that = {
      jsMonth: jsMonthIndex,
      toI: jsMonthIndex,
      name: MYW.weightCollection.monthToString(jsMonthIndex),
      weightRecords: []
    }

    that.addRecord = function(weightRecord) {
      that.weightRecords.push(weightRecord);
    };

    return that;
  },

  monthToString: function(jsMonthIndex) {
    return ["Jan", "Feb", "Mar",
            "Apr", "May", "Jun",
            "Jul", "Aug", "Sep",
            "Oct", "Nov", "Dec"][jsMonthIndex]
  },

  add: function(weightRecordSpec) {
    var weightRecord = MYW.weightRecord(weightRecordSpec);

  }
};

MYW.weightCollection.fromWeights = function(weightRecordData) {
  var that = {
    years: [],

    weightMonths: function() {
      var yearIdx;
      var monthIdx;
      for (yearIdx in that.years) {
        var year = that.years[yearIdx];
        for (monthIdx in year.months) {
          month = year.months[monthIdx];
        }
      }
    },

    add: function(weightRecordData, trigger) {
      var weightRecord = MYW.weightRecord(weightRecordData);
      var year = weightRecord.date.getYear(), month = weightRecord.date.getMonth()
      this.years[year] = this.years[year] || MYW.weightCollection.year(year);
      this.years[year].addRecord(weightRecord);
      // this.years[year].months[month] = this.years[year].months[month] || MYW.weightCollection.month(month);
      // this.years[year].months[month].addRecord(weightRecord);

      if (trigger || trigger == undefined) {
        MYW.weightMonthsDropdown.update(weightRecord.date);
      }
    },

    focusDate: function(year, month) {
      if (month.weightRecords.length > 0) {
        return month.weightRecords[0].date.toDateString();
      } else {
        return (new Date(year.jsYear, month.jsMonth, 1)).toDateString();
      }
    }
  }

  var idx;
  for (idx in weightRecordData) {
    weightRecord = weightRecordData[idx];
    that.add(weightRecord, false);
  }

  var today = new Date;
  var year = today.getYear(), month = today.getMonth();
  that.years[year] = that.years[year] || MYW.weightCollection.year(year);
  that.years[year].months[month] = that.years[year].months[month] || MYW.weightCollection.month(month);

  return that;
};


if (typeof(MYW) == 'undefined') {
  MYW = {};
}

MYW.weightMonthsDropdown = {
  update: function(selectedDate) {
    var dropdown = $('#month_for_weight_list');
    if (selectedDate == undefined) {
      selectedDate = Date.parse('today');
    }

    dropdown.find('optgroup').remove();

    for (var yearIdx in MYW.weights.years) {
      year = weightCollection.years[yearIdx];
      this.addYear(dropdown, year, selectedDate);
    }
  },

  addYear: function(dropdown, year, selectedDate) {
    var optgroup = document.createElement('optgroup');
    optgroup.setAttribute('label', year.name);
    dropdown.append(optgroup);

    for (var monthIdx in year.months) {
      month = year.months[monthIdx];
      this.addMonth(optgroup, year, month, selectedDate);
    }
  },

  addMonth: function(optgroup, year, month, selectedDate) {
    var monthDescription = month.name + " '" + year.shortName + " (" + month.weightRecords.length + ")"

    var option = document.createElement("option");
    option.setAttribute("value", MYW.weights.focusDate(year, month));
    option.innerHTML = monthDescription;

    if (selectedDate.getYear() == year.jsYear && selectedDate.getMonth() == month.jsMonth) {
      option.setAttribute("selected", "selected");
    }

    optgroup.appendChild(option);
  }
}


if (typeof(MYW) == 'undefined') {
  MYW = {};
}

MYW.weightRecord = function(spec) {
  my = {
    weight: spec.weight
  };

  if (spec.date instanceof Date) {
    my.date = spec.date;
  } else {
    my.date = Date.parse(spec.date);
  }

  var that = {
    weight: my.weight,
    date: my.date
  };

  return that;
};
