var IndexCalculator = Class.create({

    initialize: function(fieldid, one, two, three, four) {
        this.fieldid = fieldid;
        this.protein = one;
        this.fibre = two;
        this.fat = three;
        this.weight = four;
        $(one).observe('change', this.calculate.bind(this));
        $(two).observe('change', this.calculate.bind(this));
        $(three).observe('change', this.calculate.bind(this));
        $(four).observe('change', this.calculate.bind(this));
        this.calculate(this);
    },

    calculate: function(event) {
        var result;
	      var valueProtein;
        var valueFibre;
        var valueFat;
        var valueWeight;
        valueProtein = this.toNumber(this.protein, 10, 30);
        valueFibre = this.toNumber(this.fibre, 1, 15);
        valueFat = this.toNumber(this.fat, 0.1, 8.0);
        valueWeight = this.toNumber(this.weight, 2, 30);
        result = 0.2763 * valueProtein + 0.3500 * valueFibre + 0.1239 * valueFat + 0.3658 * valueWeight
        $(this.fieldid).setValue(result);
    },
    
    toNumber: function(field, lower, upper) {
        var value;
        value = parseFloat($(field).getValue());
        if (isNaN(value) || value < lower || value > upper) {
          $(field).setValue(lower);
          alert("Enter a value between " + lower + " and " + upper + ".");
          value = lower;
        }
        return value;
    }
});

Event.observe(window, 'load', function() {
  new IndexCalculator("one_mltvi", "one_crude_protein", "one_crude_fibre", "one_fat", "one_seed_weight");
  new IndexCalculator("two_mltvi", "two_crude_protein", "two_crude_fibre", "two_fat", "two_seed_weight");
  new IndexCalculator("three_mltvi", "three_crude_protein", "three_crude_fibre", "three_fat", "three_seed_weight");
  new IndexCalculator("four_mltvi", "four_crude_protein", "four_crude_fibre", "four_fat", "four_seed_weight");
  new IndexCalculator("five_mltvi", "five_crude_protein", "five_crude_fibre", "five_fat", "five_seed_weight");
});
