// Polluting the global namespace since I can't use "this" inside an ajax callback function
function updateSelectWidth(el) {
  var maxlength = 0;
  for (var i=0; i < el.options.length; i++) {
    if (maxlength < el[i].text.length ) maxlength = el[i].text.length;
  }

  el.style.width = maxlength * 10;
}

var AutoForm = Class.create({

  violation_descriptions : {
    ticket   : ['Select One', 'Defective Equipment', 'Failure to Obey Signal', 'Speeding Violation', 'Violation Not Listed'],
    accident : ['Select One', 'Vehicle Hit Vehicle', 'Vehicle Hit Pedestrian', 'Vehicle Hit Property', 'Other Vehicle Hit Yours', 'Other at Fault Accident', 'Other Not at Fault Accident'],
    claim    : ['Select One', 'Fire/Hail/Water Damage', 'Vandalism Damage', 'Vehicle Hit Animal', 'Vehicle Stolen', 'Windshield Damage', 'Claim Not Listed'],
    dui      : ['DUI/DWI']
  },

  initialize : function() {
    this.violations = 0;
    this.initializeEvents();
  },

  initializeEvents : function() {
    /* Submits */
    Event.observe(document, 'keypress', this.onInterceptReturns.bindAsEventListener(this));

    var submits = $$('input.submit');
    for (var i=0; i < submits.length; i++) {
      Event.observe(submits[i], 'click', this.onRequestMyQuote.bindAsEventListener(this));
    };

    var submits = $$('input.skip');
    for (var i=0; i < submits.length; i++) {
      Event.observe(submits[i], 'click', this.onSkipThis.bindAsEventListener(this));
    };

    /* Load vehicle options via ajax */
    if ( $('lead_current_vehicle_id') ) {
      var num = $F('lead_current_vehicle_id');

      $('lead_vehicle' + num + '_make').disabled = true;
      $('lead_vehicle' + num + '_model').disabled = true;
      $('lead_vehicle' + num + '_submodel').disabled = true;

      $('lead_vehicle' + num + '_year').observe('change', this.onChangeVehicleYear.bindAsEventListener(this));
      $('lead_vehicle' + num + '_make').observe('change', this.onChangeVehicleMake.bindAsEventListener(this));
      $('lead_vehicle' + num + '_model').observe('change', this.onChangeVehicleModel.bindAsEventListener(this));
    }

    if ( $('lead_violation1_description') ) {
      this.addViolationEventHandlers(1);
      this.addViolationEventHandlers(2);
      this.addViolationEventHandlers(3);
      this.addViolationEventHandlers(4);
    }

    if ( $('submit-add-violation') ) {
      $('submit-add-violation').observe('click', this.onAddViolation.bindAsEventListener(this));

      var deletes = $$('.delete-violation');
      for (var i=0; i < deletes.length; i++) {
        Event.observe(deletes[i], 'click', this.onDeleteViolation.bindAsEventListener(this));
      };
    }

    /* Other Events */
    if ( $('lead_has_existing_carrier_1') ) {
      $('lead_has_existing_carrier_1').observe('click', this.onChangeCurrentlyInsured.bindAsEventListener(this));
      $('lead_has_existing_carrier_0').observe('click', this.onChangeCurrentlyInsured.bindAsEventListener(this));
      this.onChangeCurrentlyInsured();
    }

    /* Handle window closing */
    // window.onbeforeunload = this.onUnload;
  },

  addViolationEventHandlers : function(num) {
    $('lead_violation' + num + '_type').observe('change', this.onChangeViolationType.bindAsEventListener(this));
    $('lead_violation' + num + '_description').disabled = true;
    //setup amount paid field
    this.resetViolationAmountPaid(num);
  },

  /* --------------------------------------------------------------------------
   * Event Handlers
   * ------------------------------------------------------------------------*/

   onUnload : function() {
     // What?! jQuery from within Prototype? This is crazy I know.
     jQuery("#exit-message").trigger('click');
     window.onbeforeunload = null;
     return "Hit CANCEL to get access to rate quotes from leading providers right now.";
   },
   
  onInterceptReturns : function(e) {
    if (e.keyCode == Event.KEY_RETURN) {
      this.onRequestMyQuote(e);
      if (e) Event.stop(e);
    }
  },

  onRequestMyQuote : function(e) {
    var is_valid = this.validateForm();
    if (is_valid) {
      window.onbeforeunload = null;
    } else {
      Event.stop(e);
      this.focusOnFirstInvalidElement();
    }
  },

  onSkipThis : function(e) {
    $('auto-insurance-form').reset();
    window.onbeforeunload = null;
  },

  onAddViolation : function(e) {
    if (this.violations < 4) {
      this.violations++;
      if (this.violations == 4) $('submit-add-violation').hide();
      $$('.violation').find(function(el) { return !el.visible(); }).show();
    }

    if (e) Event.stop(e);
  },

  onDeleteViolation : function(e) {
    var el  = Event.element(e);
    var num = el.id.match(/(\d)/)[1];

    // Show Add Violation button
    this.violations--;
    $('submit-add-violation').show();

    this.deleteViolation(num);
  },

  // If the next violation is visible, we shift that violation into this violation's
  // place and recurse on the next violation.
  // If the next violation is not visible we reset and hide this violation
  deleteViolation : function(num) {
    var next_num = 1 * num + 1; // Convert to integer and add 1
    if ( next_num <= 4 && $('violation' + next_num).visible() ) {
      this.shiftViolationUp(next_num);
      this.deleteViolation(next_num);
    } else {
      this.resetAndHideViolation(num);
    }
  },

  shiftViolationUp : function(num) {
    var dest_num = 1 * num - 1; // Convert to integer and subtract 1

    $('lead_violation' + dest_num + '_driver_id').selectedIndex  = $('lead_violation' + num + '_driver_id').selectedIndex;
    $('lead_violation' + dest_num + '_mm_on').selectedIndex      = $('lead_violation' + num + '_mm_on').selectedIndex;
    $('lead_violation' + dest_num + '_yyyy_on').selectedIndex    = $('lead_violation' + num + '_yyyy_on').selectedIndex;
    $('lead_violation' + dest_num + '_type').selectedIndex       = $('lead_violation' + num + '_type').selectedIndex;

    //move up amount paif if type equals claim
    if($F("lead_violation" + dest_num + "_type") == "claim") {
      $("lead_violation" + dest_num + "_amount_paid").disabled = false;
      $("lead_violation" + dest_num + "_amount_paid").value = $F("lead_violation" + num + "_amount_paid")
      $("lead_violation" + num + "_amount_paid").disabled = true;
    //reset if not claim
    } else {
      this.resetViolationAmountPaid(dest_num);
    }

    //clear out error msg if something was selected
    this.moveErrors("lead_violation" + dest_num + "_driver_id_error", "lead_violation" + num + "_driver_id_error");
    this.moveErrors("lead_violation" + dest_num + "_on_error", "lead_violation" + num + "_on_error");
    this.moveErrors("lead_violation" + dest_num + "_type_error", "lead_violation" + num + "_type_error");
    this.moveErrors("lead_violation" + dest_num + "_description_error", "lead_violation" + num + "_description_error");
    this.moveErrors("lead_violation" + dest_num + "_amount_paid_error", "lead_violation" + num + "_amount_paid_error");

    // Change description
    this.changeViolationDescription( dest_num, $F('lead_violation' + dest_num + '_type') );
    $("lead_violation" + dest_num + "_description").selectedIndex = $("lead_violation" + num + "_description").selectedIndex;
    $("lead_violation" + dest_num + "_description").options[$("lead_violation" + num + "_description").selectedIndex].setAttribute("selected", true);
  },

  moveErrors : function(dest_error_el, error_el) {
    if($(error_el).visible()) {
      $(error_el).hide();
      $(dest_error_el).className = $(error_el).className;
      $(dest_error_el).innerHTML = $(error_el).innerHTML;
      $(dest_error_el).show();
    } else {
      $(error_el).hide();
      $(dest_error_el).hide();
    }
  },

  resetAndHideViolation : function(num) {
    $('violation' + num).hide();

    $('lead_violation' + num + '_driver_id').selectedIndex  = 0;
    $('lead_violation' + num + '_mm_on').selectedIndex      = 0;
    $('lead_violation' + num + '_yyyy_on').selectedIndex    = 0;
    $('lead_violation' + num + '_type').selectedIndex       = 0;
    this.changeViolationDescription(num, null);
    $('lead_violation' + num + '_description').disabled     = true;

    // Clear any errors
    this.refreshValidationAdvice('lead_violation' + num + '_driver_id', true, '');
    this.refreshValidationAdvice('lead_violation' + num + '_on', true, '');
    this.refreshValidationAdvice('lead_violation' + num + '_type', true, '');
    this.resetViolationAmountPaid(num);
  },

  onChangeViolationType : function(e) {
    var el             = Event.element(e);
    var num            = el.id.match(/(\d)/)[1];
    var violation_type = $F(el)

    $("lead_violation" + num + "_description_error").hide();
    if (el.selectedIndex == 0) {
      this.changeViolationDescription(num, null);
      $('lead_violation' + num + '_description').disabled = true
      this.resetViolationAmountPaid(num);
    } else {
      this.changeViolationDescription(num, violation_type);
      $("lead_violation" + num + "_description_error").addClassName("validate-selected");
      if(violation_type == "claim") {
        $("lead_violation" + num + "_amount_paid").disabled = false;
        $("lead_violation" + num + "_amount_paid_error").addClassName("validate-claim-amount");
      } else {
        this.resetViolationAmountPaid(num);
      }
    }
  },

  resetViolationAmountPaid : function(num) {
    $("lead_violation" + num + "_amount_paid").disabled = true;
    $("lead_violation" + num + "_amount_paid").value = "";
    $("lead_violation" + num + "_amount_paid_error").removeClassName("validate-claim-amount");
    $("lead_violation" + num + "_amount_paid_error").hide();
  },

  changeViolationDescription : function(num, violation_type) {
    var options = this.violation_descriptions[violation_type];
    if (options == null) options = ['Select One'];
    var select  = $('lead_violation' + num + '_description');
    this.clearSelectOptions(select);
    this.addSelectOptionsFromArray(select, options);
    // updateSelectWidth(select);

    // Disable again if they re-selected the prompt option
    if (options[0] == 'Description' || ($("lead_violation" + num + "_type").selectedIndex == 0) ) {
      select.disabled = true;
      $("lead_violation" + num + "_description_error").removeClassName("validate-selected");
      $("lead_violation" + num + "_description_error").hide();
    } else {
      select.disabled = false;
      $("lead_violation" + num + "_description_error").addClassName("validate-selected");
    }
  },

  focusOnFirstInvalidElement : function() {
    var parent = $$('.advice').find(function(el) { return el.visible(); }).parentNode;
    $(parent).scrollTo();
  },

  onChangeVehicleYear : function(e) {
    var num = $F('lead_current_vehicle_id');
    this.disableAndResetSelect('lead_vehicle' + num + '_model');
    this.disableAndResetSelect('lead_vehicle' + num + '_submodel');

    var el = Event.element(e);
    if (el.selectedIndex == 0) {
      this.disableAndResetSelect('lead_vehicle' + num + '_make');
    } else {
      this.loadVehicleOptions("/vehicles?year=" + $F('lead_vehicle' + num + '_year'), 'lead_vehicle' + num + '_make', 'Vehicle Make');
    }
  },

  onChangeVehicleMake : function(e) {
    var num = $F('lead_current_vehicle_id');
    this.disableAndResetSelect('lead_vehicle' + num + '_submodel');

    var el = Event.element(e);
    if (el.selectedIndex == 0) {
      this.disableAndResetSelect('lead_vehicle' + num + '_model');
    } else {
      this.loadVehicleOptions("/vehicles?year=" + $F('lead_vehicle' + num + '_year') + "&make=" + $F('lead_vehicle' + num + '_make'), 'lead_vehicle' + num + '_model', 'Vehicle Model');
    }
  },

  onChangeVehicleModel : function(e) {
    var num = $F('lead_current_vehicle_id');

    var el = Event.element(e);
    if (el.selectedIndex == 0) {
      this.disableAndResetSelect('lead_vehicle' + num + '_submodel');
    } else {
      $('lead_vehicle' + num + '_submodel_loading').show();
      new Ajax.Request("/vehicles?year=" + $F('lead_vehicle' + num + '_year') + "&make=" + $F('lead_vehicle' + num + '_make') + "&model=" + $F('lead_vehicle' + num + '_model'), {
        method: 'get',
        evalJSON: true,
        onSuccess: function(transport, json) {
          var el = $('lead_vehicle' + num + '_submodel');

          // Clear options
          while ( el.hasChildNodes() ) {
            el.removeChild( el.firstChild );
          }

          // Add first option
          json.unshift({name: 'Vehicle Submodel', code: 'blank'})

          // Add the rest of the options
          for (var i=0; i < json.length; i++) {
            var opt = document.createElement('OPTION');
            opt.setAttribute('value',json[i].name);
            opt.setAttribute('title',json[i].name);
            var text = document.createTextNode(json[i].name);
            opt.appendChild(text);
            el.appendChild(opt);
          };

          updateSelectWidth(el);
          el.disabled = false;

        }, onComplete : function(transport) {
          $('lead_vehicle' + num + '_submodel_loading').hide();

          var el = $('lead_vehicle' + num + '_submodel');
          if ( el.options.length == 2 ) {
            $('lead_vehicle' + num + '_submodel_error').hide();
            // el.selectedIndex = 1;
            el.options[1].setAttribute("selected", true);
          } else {
            // el.selectedIndex = 0;
            el.options[0].setAttribute("selected", true);
          }
        }
      });
    }
  },

  disableAndResetSelect : function(el) {
    $(el).selectedIndex = 0;
    $(el).disabled = true;
  },

  loadVehicleOptions : function(url, select_to_update, title) {
    $(select_to_update + '_loading').show();

    new Ajax.Request(url, {
      method: 'get',
      evalJSON: true,
      onSuccess: function(transport, json) {
        var el = $(select_to_update);

        // Clear options
        while ( el.hasChildNodes() ) {
          el.removeChild( el.firstChild );
        }

        // Add first option
        var opt = document.createElement('OPTION');
        opt.setAttribute('value','blank');
        var text = document.createTextNode(title);
        opt.appendChild(text);
        el.appendChild(opt);

        // Add the rest of the options
        for (var i=0; i < json.length; i++) {
          var opt = document.createElement('OPTION');
          opt.setAttribute('value',json[i]);
          opt.setAttribute('title',json[i]);
          var text = document.createTextNode(json[i]);
          opt.appendChild(text);
          el.appendChild(opt);
        };

        updateSelectWidth(el);
        el.disabled = false;
      }, onComplete : function(transport) { $(select_to_update + '_loading').hide(); }
    });
  },

  clearSelectOptions : function(el) {
    while ( el.hasChildNodes() ) {
       el.removeChild( el.firstChild );
    }
  },

  addSelectOptionsFromArray : function(el, a) {
    for (var i=0; i < a.length; i++) {
      var opt = document.createElement('OPTION');
      opt.setAttribute('value',a[i]);
      opt.setAttribute('title',a[i]);
      var text = document.createTextNode(a[i]);
      opt.appendChild(text);
      el.appendChild(opt);
    };
  },

  onChangeCurrentlyInsured : function() {
    if ( $('lead_has_existing_carrier_1').checked ) {
      $$('.existing-carrier').invoke('show');
    } else {
      $$('.existing-carrier').invoke('hide');
      $('lead_existing_carrier').selectedIndex       = 0;
      $('lead_policy_expires_mm_on').selectedIndex   = 0;
      $('lead_policy_expires_dd_on').selectedIndex   = 0;
      $('lead_policy_expires_yyyy_on').selectedIndex = 0;
      $('lead_carrier_years').selectedIndex          = 2; // Default to 1 year
      $('lead_carrier_months').selectedIndex         = 1; // Default to 0 months
      this.refreshValidationAdvice('lead_existing_carrier', true, '')
      this.refreshValidationAdvice('lead_policy_expires_on', true, '')
      this.refreshValidationAdvice('lead_carrier_years_months', true, '')
    }
  },


  /* --------------------------------------------------------------------------
   * Validations
   * ------------------------------------------------------------------------*/

  validateForm : function() {
    var is_valid = true;
    switch ( $F('form_state') ) {
      case 'step1'        : is_valid = this.validateStep1(); break;
      case 'add_driver'   : is_valid = this.validateAddDriver(); break;
      case 'add_vehicle'  : is_valid = this.validateAddVehicle(); break;
      case 'add_violation': is_valid = this.validateAddViolation(); break;
    }
    return is_valid;
  },

  validateStep1 : function() {
    var valid_inputs = [
      this.validateVehicle(1),
      this.validateCoverageLevel(),
      this.validateDriver(1),
      this.validateHasExistingCarrier(),
      this.validateCurrentInsurance(),
      this.validateContact()
    ];

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },

  validateAddDriver : function() {
    var num = $F('lead_current_driver_id');
    var valid_inputs = [
      this.validateRelationshipToApplicant(num),
      this.validateDriverFirstName(num),
      this.validateDriver(num)
    ];

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },

  validateAddVehicle : function() {
    var num = $F('lead_current_vehicle_id');
    var valid_inputs = [
      this.validateVehicle(num)
    ];

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },

  validateAddViolation : function() {
    var valid_inputs = [];

    // Find all visible violations and validate them
    var violations = $$('.violation').select(function(el) { return el.visible(); });

    for (var i=0; i < violations.length; i++) {
      var num = violations[i].id.match(/(\d)/)[1];
      valid_inputs.push(this.validateViolation(num));
    };

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },

  validateViolation : function(num) {
    var valid_inputs = [
      this.validateDriverInvolved(num),
      this.validateViolationOn(num),
      this.validateViolationType(num),
      this.validateViolationDescription(num),
      this.validateViolationAmountPaid(num)
    ];

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },

  validateVehicle : function(num) {
    var valid_inputs = [
      this.validateVehicleYear(num),
      this.validateVehicleMake(num),
      this.validateVehicleModel(num),
      this.validateVehicleSubmodel(num),
      this.validateOwnershipStatus(num),
      this.validateVehiclePrimaryUse(num),
      this.validateDailyMileage(num),
      this.validateAnnualMileage(num),
      this.validateComprehensiveDeductible(num),
      this.validateCollisionDeductible(num),
      this.validatePrimaryDriver(num)
    ];

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },
  
  validateDriver : function(num) {
    var valid_inputs = [
      this.validateGender(num),
      this.validateDateOfBirth(num),
      this.validateMaritalStatus(num),
      this.validateOccupation(num),
      this.validateEducationLevel(num),
      this.validateAgeLicensed(num),
      this.validateCurrentLicenseStatus(num)
    ];

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },

  validateContact : function(num) {
    var valid_inputs = [
      this.validateFirstName(),
      this.validateLastName(),
      this.validateAddressLine1(),
      this.validateZip(),
      this.validatePhone1(),
      this.validateEmail(),
      this.validateCreditRating(),
      this.validateResidenceStatus(),
      this.validateResidenceLength()
    ];

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },

  validateCurrentInsurance : function() {
    if ( !$('lead_has_existing_carrier_1').checked ) return true;

    var valid_inputs = [
      this.validateExistingCarrier(),
      this.validatePolicyExpiresOn(),
      this.validateCarrierYearsMonths()
    ];

    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  },

  validateVehicleYear : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_year', 'Please select a year');
  },

  validateVehicleMake : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_make', 'Please select a make');
  },

  validateVehicleModel : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_model', 'Please select a model');
  },

  validateVehicleSubmodel : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_submodel', 'Please select a submodel');
  },

  validateOwnershipStatus : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_ownership_status', 'Please select a value');
  },

  validateVehiclePrimaryUse : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_primary_use', 'Please select a value');
  },
  
  validateDailyMileage : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_daily_mileage', 'Please select a value');
  },

  validateAnnualMileage : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_annual_mileage', 'Please select a value');
  },

  validateComprehensiveDeductible : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_comprehensive_deductible', 'Please select a value');
  },

  validateCollisionDeductible : function(num) {
    return this.validateSelection('lead_vehicle' + num + '_collision_deductible', 'Please select a value');
  },

  validatePrimaryDriver : function(num) {
    if ( $('lead_vehicle' + num + '_primary_driver_id') ) {
      return this.validateSelection('lead_vehicle' + num + '_primary_driver_id', 'Please select a driver');
    } else {
      return true;
    }
  },

  validateCoverageLevel : function() {
    return this.validateSelection('lead_coverage_level', 'Please select a value');
  },

  validateMaritalStatus : function(num) {
    return this.validateSelection('lead_insured' + num + '_marital_status', 'Please select a marital status');
  },

  validateOccupation : function(num) {
    return this.validateSelection('lead_insured' + num + '_occupation', 'Please select an occupation');
  },

  validateEducationLevel : function(num) {
    return this.validateSelection('lead_insured' + num + '_education_level', 'Please select an education level');
  },

  validateAgeLicensed : function(num) {
    var el = 'lead_insured' + num + '_age_licensed';
    var valid = Validation.get('validate-age-licensed').test($F(el), $(el));
    this.refreshValidationAdvice(el, valid, 'Please enter a valid age');
    return valid;
  },

  validateCurrentLicenseStatus : function(num) {
    return this.validateSelection('lead_insured' + num + '_license_status', 'Please select a license status');
  },

  validateCreditRating : function() {
    return this.validateSelection('lead_credit_rating', 'Please select a credit rating');
  },

  validateResidenceStatus : function() {
    return this.validateSelection('lead_residence_status', 'Please select a residence status');
  },

  validateResidenceLength : function() {
    return this.validateSelection('lead_residence_length_in_months', 'Please select a residence length');
  },

  validateExistingCarrier : function() {
    return this.validateSelection('lead_existing_carrier', 'Please select your current insurance company');
  },

  validatePolicyExpiresOn : function() {
    var el = 'lead_policy_expires_mm_on';
    var valid = Validation.get('validate-policy-expires-on').test($F(el), $(el));
    this.refreshValidationAdvice('lead_policy_expires_on', valid, 'Please select a valid future date');
    return valid;
  },

  validateCarrierYearsMonths : function() {
    var el = 'lead_carrier_years';
    var valid = Validation.get('validate-all-selection').test($F(el), $(el));
    this.refreshValidationAdvice('lead_carrier_years_months', valid, 'Please select the number of years and months');
    return valid;
  },

  validateDriverFirstName : function(num) {
    var valid = Validation.get('validate-name').test($F('lead_insured' + num + '_first_name'));
    this.refreshValidationAdvice('lead_insured' + num + '_first_name', valid, 'Please enter a first name');
    return valid;
  },

  validateRelationshipToApplicant : function(num) {
    return this.validateSelection('lead_insured' + num + '_relationship_to_insured', 'Please select an option');
  },

  validateDriverInvolved : function(num) {
    return this.validateSelection('lead_violation' + num + '_driver_id', 'Please select a driver');
  },

  validateViolationOn : function(num) {
    var el = 'lead_violation' + num + '_mm_on';
    var valid = Validation.get('validate-all-selection').test($F(el), $(el));
    this.refreshValidationAdvice('lead_violation' + num + '_on', valid, 'Please select a date');
    return valid;
  },

  validateViolationType : function(num) {
    return this.validateSelection('lead_violation' + num + '_type', 'Please select a type');
  },

  validateViolationDescription : function(num) {
    var el = 'lead_violation' + num + '_description';
    if ($(el).disabled == true) return true;
    var valid = $F(el) != 'Select One';
    this.refreshValidationAdvice(el, valid, 'Please select a description');
    return valid;
  },

  validateViolationAmountPaid : function(num) {
    var el = 'lead_violation' + num + '_type';
    if ($(el).value != "claim") return true;

    var el = 'lead_violation' + num + '_amount_paid';
    var valid = Validation.get('validate-claim-amount').test($F(el), $(el));
    this.refreshValidationAdvice('lead_violation' + num + '_amount_paid', valid, 'Please enter a valid amount');
    return valid;
  },

  validateSelection : function(el, msg) {
    var valid = Validation.get('validate-selection').test($F(el), $(el));
    this.refreshValidationAdvice(el, valid, msg);
    return valid;
  }
});

AutoForm.addMethods(ValidationHelper);

/* Validate the form */
if (!(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 6)) {
  FastInit.addOnLoad(function() {
    var auto_form = new AutoForm();
  });
}
