var LifeForm = Class.create({
  initialize: function() {
    this.initializeEvents();
  },

  initializeEvents : function() {
    /* Submits */
    Event.observe(document, 'keypress', this.onInterceptReturns.bindAsEventListener(this));
    Event.observe('submit', 'click', this.onRequestMyQuote.bindAsEventListener(this));

    if ($('lead_life_insurance_type')) {
      Event.observe('lead_life_insurance_type', 'change', this.onChangeLifeInsuranceType.bindAsEventListener(this));
      this.onChangeLifeInsuranceType();
    } 

    if ( $('lead_has_existing_carrier_1') ) {
      Event.observe('lead_has_existing_carrier_1', 'click', this.onChangeCurrentlyInsured.bindAsEventListener(this));
      Event.observe('lead_has_existing_carrier_0', 'click', this.onChangeCurrentlyInsured.bindAsEventListener(this));
      this.onChangeCurrentlyInsured();
    }

    if ( $('lead_has_pre_existing_conditions_1') ) {
      Event.observe('lead_has_pre_existing_conditions_1', 'click', this.onChangePreExistingConditions.bindAsEventListener(this));
      Event.observe('lead_has_pre_existing_conditions_0', 'click', this.onChangePreExistingConditions.bindAsEventListener(this));
      this.onChangePreExistingConditions();
    }
    
    if ( $('lead_takes_medications_1') ) {
      Event.observe('lead_takes_medications_1', 'click', this.onChangeTakesMedications.bindAsEventListener(this));
      Event.observe('lead_takes_medications_0', 'click', this.onChangeTakesMedications.bindAsEventListener(this));
      this.onChangeTakesMedications();
    }
    if ( $('lead_gender1_m') ) {
      Event.observe($('lead_gender1_m').parentNode, 'click', this.onClickGender.bindAsEventListener(this));
      Event.observe($('lead_gender1_f').parentNode, 'click', this.onClickGender.bindAsEventListener(this));
    }

    $$('a.back').each( function(el) {
      // remove the exit message if they click back link
      // using mousedown becasue the link already has an onclick set in the html
      Event.observe(el, 'mousedown', function(){window.onbeforeunload=null;})
    });
    
    $$(".textfield").each( this.addDefaultValue );
    
    $$(".textfield").each(function(el) {
      el.observe('focus', function(event) {
        var el = Event.element(event);
        if ($F(el) == el.title) {
          el.value = '';
          el.removeClassName("default-text");
        }
      });

      el.observe('blur', function(event) {
        var el = Event.element(event);
        if ($F(el) == '') {
          el.value = el.title;
          el.addClassName("default-text");
        }
      });
    });

    /* Handle window closing */
    if ($('exit-message')) window.onbeforeunload = this.onUnload;
  },

  onUnload : function() {
    // What?! jQuery from within Prototype? This is crazy I know.
    jQuery("#exit-message").trigger('click');
    // Re-position popup...
    jQuery("#colorbox").css({ top:jQuery(window).scrollTop() + 30 });

    window.onbeforeunload = null;
    return "Hit CANCEL to get access to rate quotes from leading providers right now.";
  },

  onChangeCurrentlyInsured : function() {
    if ( $('lead_has_existing_carrier_1').checked ) {
      $('existing_carrier_row').show()
    } else {
      $('existing_carrier_row').hide();
      $('lead_existing_carrier').selectedIndex = 0;
    }
  },
  
  onChangeTakesMedications : function() {
    if ( $('lead_takes_medications_1').checked ) {
      $('insured1_current_medications_detail_row').show();
    } else {
      $('insured1_current_medications_detail_row').hide();
      $('lead_insured1_current_medications_detail').clear();
    }
  },
  
  onChangePreExistingConditions : function() {
    if ( $('lead_has_pre_existing_conditions_1').checked ) {
      $('pre_existing_conditions_row').show();
    } else {
      $('pre_existing_conditions_row').hide();
      var conditions = $('pre_existing_conditions_row').getElementsByTagName('INPUT');
	    $A(conditions).each(function(n) { n.checked = false; });
    }
  },

  onChangeLifeInsuranceType : function() {
    /(term)/i.test( $F("lead_life_insurance_type") ) ? $("length-of-term-field-set").show() : $("length-of-term-field-set").hide();
  },
  
  addDefaultValue: function(el) {
    if ($F(el) == '') {
      el.value = el.title;
    }

    if ($F(el) == el.title) {
      el.addClassName("default-text");      
    }
  },
  
  removeDefaultValue: function(el) {
    if ($F(el) == el.title) {
      el.value = '';
      el.removeClassName("default-text");
    }
  },

  /* Event Handlers */
  onInterceptReturns : function(e) {
    if (e.keyCode == Event.KEY_RETURN) {
      this.onRequestMyQuote(e);
      if (e) Event.stop(e);
    }
  },
  
  onRequestMyQuote : function(e) {
    $$(".textfield").each( this.removeDefaultValue );
    var is_valid = this.validateForm();
    if (is_valid) {
      window.onbeforeunload = null;
    } else {
      Event.stop(e);
    }      
  },

  /* Validations */
  validateForm : function() {
    var step = $F('lead-state');
    
    if (step == 'step1') {
      var valid_inputs = [
        this.validateInsuredNew(1),
        this.validateFirstName(),
        this.validateLastName(),
        this.validateEmail(),
        this.validatePhone1(),
        this.validateZip(),
        this.validateSmoker(),
        this.validatePrivacyPolicy()
      ];
    } else if (step == 'step2') {
      var valid_inputs = [
        this.validateAddressLine1()
      ];
    } else if (step == 'step3') {
      var valid_inputs = [
        this.validateCurrentlyInsured(),
        this.validateMedications(),
        this.validatePreExistingConditions()
      ];
    } else {
      return true;
    }
    
    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  }
});

LifeForm.addMethods(ValidationHelper);

// Overriding some methods from ValidationHelper because we want them to behave
// a little differently
LifeForm.addMethods({
  validateMedications : function() {
    var valid = true;
    if ($F('lead_takes_medications_1')) {
      valid = Validation.get('required').test($F('lead_insured1_current_medications_detail'));
    }

    var error_element = $('lead_insured1_current_medications_detail_error');
    if (valid) {
      if ( error_element.hasClassName("validation-advice") ) error_element.removeClassName("validation-advice");
    } else {
      if ( !error_element.hasClassName("validation-advice") ) error_element.addClassName("validation-advice");
    }
    return valid;
  },

  validatePreExistingConditions : function() {
    var valid = true;
    if ( $F('lead_has_pre_existing_conditions_1') ) {
      var conditions = $('pre_existing_conditions_row').getElementsByTagName('INPUT');
      valid = $A(conditions).any(function(n) { return $F(n) != null; });
    }
    
    var error_element = $('lead_pre_existing_conditions_error');
    if (valid) {
      if ( error_element.hasClassName("validation-advice") ) error_element.removeClassName("validation-advice");
    } else {
      if ( !error_element.hasClassName("validation-advice") ) error_element.addClassName("validation-advice");
    }
    return valid;
  },

  onClickGender : function(e) {
    var lbl = Event.findElement(e, 'label');
    var inpt = lbl.getElementsByTagName("input")[0];

    var rslt = /gender(\d)_(m|f)$/.exec(inpt.id);
    var gid = rslt[1];
    var opsex = (rslt[2] == 'm') ? 'f' : 'm';
    var lbl2 = $('lead_gender' + gid + '_' + opsex).parentNode;
    lbl2.className = lbl2.className.replace(/gender(m|f)_s/, "gender$1_d");
    if (inpt.checked)
      lbl.className = lbl.className.replace(/gender(m|f)_d/, "gender$1_s");
    else
      lbl.className = lbl.className.replace(/gender(m|f)_s/, "gender$1_d");
  }

});


/* Validate the form */
if (!(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 6)) {
  FastInit.addOnLoad(function() {
    var life_form = new LifeForm();
  });
}
