var HealthForm = Class.create({
  initialize: function() {
    this.children     = 0;
    this.spouse       = false;
    this.max_children = 5;
    this.lead_state   = $F("lead_state");
    this.initializeState();
  },

  initializeState : function() {
    if (this.lead_state == 'health') {
      this.initializeHealthStep();
    }
    /* Handle window closing */
    if ($('exit-message')) window.onbeforeunload = this.onUnload;
  },

  initializeHealthStep : function() {
	$("title-row").hide();
    this.hideSpouse();
    this.hideChildren();
    this.onChangePreExistingConditions();

    /* Submits */
    Event.observe(document, 'keypress', this.onInterceptReturns.bindAsEventListener(this));
    Event.observe('submit', 'click', this.onRequestMyQuote.bindAsEventListener(this));

    Event.observe('add-child', 'click', this.onAddChild.bindAsEventListener(this));
    var children = $$('.child-row .remove-insured');
    for (var i=0; i < children.length; i++) {
      Event.observe(children[i], 'click', this.onRemoveChild.bindAsEventListener(this));
    };

    Event.observe('add-spouse', 'click', this.onAddSpouse.bindAsEventListener(this));
    Event.observe('remove-spouse', 'click', this.onRemoveSpouse.bindAsEventListener(this));

    Event.observe('lead_pre_existing_0', 'click', this.onChangePreExistingConditions.bindAsEventListener(this));
    Event.observe('lead_pre_existing_1', 'click', this.onChangePreExistingConditions.bindAsEventListener(this));

    Event.observe($('lead_gender1_m').parentNode, 'click', this.onClickGender.bindAsEventListener(this));
    Event.observe($('lead_gender1_f').parentNode, 'click', this.onClickGender.bindAsEventListener(this));
  },

  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.";
  },

  /* Event Handlers */
  onInterceptReturns : function(e) {
    if (e.keyCode == Event.KEY_RETURN) {
      if (this.lead_state == 'health') {
        this.onRequestMyQuote(e);
      }
      if (e) Event.stop(e);
    }
  },

  hideSpouse : function(e) {
    $("spouse").hide();
    if (e) Event.stop(e);
  },

  hideChildren : function(e) {
    for (var i=1; i <= this.max_children; i++) { $("child-" + i).hide(); }
    if (e) Event.stop(e);
  },

  onAddSpouse : function(e) {
	$("title-row").show();
    $("spouse").show();
    $("add-spouse").hide();
    $("disabled-spouse").show();
    this.spouse = true;
    if (e) Event.stop(e);
  },

  onRemoveSpouse : function(e) {
	if (this.children == 0) $("title-row").hide();
    $("spouse").hide();
    $("add-spouse").show();
    $("disabled-spouse").hide();
    this.resetInsured(2);
    this.spouse = false;
    if (e) Event.stop(e);
  },

  onAddChild : function(e) {
    if (this.children < this.max_children) {
	  $('title-row').show();
      this.children++;
      if (this.children == this.max_children) {
        $('add-child').hide();
        $('disabled-child').show();
      }
      $$('.child-row').find(function(el) { return !el.visible(); }).show();
    }

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

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

    // Show Add Child button
    this.children--;
    $('add-child').show();
    $('disabled-child').hide();

    this.deleteChild(1 * num);
    if (this.children == 0 && this.spouse == false ) $("title-row").hide();
    if (e) Event.stop(e);
  },

  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");
  },

  // If the next child is visible, we shift that child into this child's
  // place and recurse on the next child.
  // If the next child is not visible we reset and hide this child
  deleteChild : function(num) {
    var next_num = num + 1;
    if ( next_num <= this.max_children && $('child-' + next_num).visible() ) {
      this.shiftChildrenUp(next_num);
      this.deleteChild(next_num);
    } else {
      this.resetAndHideChild(num);
    }
  },

  shiftChildrenUp : function(num) {
    var ins_num      = num + 2;
    var ins_dest_num = num + 1;

    // Form values
    $('lead_gender' + ins_dest_num + '_m').checked = $('lead_gender' + ins_num + '_m').checked;
    $('lead_gender' + ins_dest_num + '_f').checked = $('lead_gender' + ins_num + '_f').checked;

    $('lead_dob' + ins_dest_num + '_mm_on').value   = $F('lead_dob' + ins_num + '_mm_on');
    $('lead_dob' + ins_dest_num + '_dd_on').value   = $F('lead_dob' + ins_num + '_dd_on');
    $('lead_dob' + ins_dest_num + '_yyyy_on').value = $F('lead_dob' + ins_num + '_yyyy_on');

    $('lead_insured' + ins_dest_num + "_height_total_inches").selectedIndex = $('lead_insured' + ins_num + "_height_total_inches").selectedIndex;
    $('lead_insured' + ins_dest_num + '_weight').value                = $F('lead_insured' + ins_num + '_weight');

    $('lead_is_smoker' + ins_dest_num).checked = $('lead_is_smoker' + ins_num ).checked;
    $('lead_is_student' + ins_dest_num).checked = $('lead_is_student' + ins_num ).checked;

    // Error messages
    this.moveErrors("lead_gender" + ins_dest_num + "_error", "lead_gender" + ins_num + "_error");
    this.moveErrors("lead_dob" + ins_dest_num + "_on_error", "lead_dob" + ins_num + "_on_error");
    this.moveErrors("lead_insured" + ins_dest_num + "_height_error", "lead_insured" + ins_num + "_height_error");
    this.moveErrors("lead_insured" + ins_dest_num + "_weight_error", "lead_insured" + ins_num + "_weight_error");
  },

  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();
    }
  },

  resetAndHideChild : function(num) {
    this.resetInsured(num + 2);
    $('child-' + num).hide();
  },

  onChangePreExistingConditions : function() {
	var slide = (typeof arguments[0] != 'undefined') ? true : false;
    if ( $('lead_pre_existing_1').checked ) {
      (slide) ? $('pre_existing_conditions_row').slideDown({duration:0.6}) : $('pre_existing_conditions_row').show();
    } else {
      (slide) ? $('pre_existing_conditions_row').slideUp({duration:0.6}) : $('pre_existing_conditions_row').hide();
      var conditions = $('pre_existing_conditions_row').getElementsByTagName('INPUT');
	    $A(conditions).each(function(n) { n.checked = false; });
    }
  },

  resetInsured : function(insured) {
    $('lead_gender' + insured + '_m').checked = false;
    $('lead_gender' + insured + '_f').checked = false;
    $('lead_insured' + insured + '_height_total_inches').clear();

    $('lead_insured' + insured + '_weight').clear();

    $('lead_dob' + insured + '_mm_on').clear();
    $('lead_dob' + insured + '_dd_on').clear();
    $('lead_dob' + insured + '_yyyy_on').clear();

    $('lead_is_smoker' + insured).checked = false;
    $('lead_is_student' + insured).checked = false;

    $('lead_insured' + insured + '_height_error').hide();
    $('lead_insured' + insured + '_weight_error').hide();
    $('lead_dob' + insured + '_on_error').hide();
  },

  onRequestMyQuote : function(e) {
    var is_valid = this.validateHealthStep();

    if (is_valid) {
      window.onbeforeunload = null;
    } else {
      Event.stop(e);
    }
  },

  /* Validations */
  validateHealthStep : function() {
    var valid_inputs = [
      // insured 1
      this.validateGenderRadio(1),
      this.validateHeightCombined(1),
      this.validateWeight(1),
      this.validateDateOfBirth(1),

      // contact info
      this.validateFirstName(),
      this.validateLastName(),
      this.validateAddressLine1(),
      this.validateState(),
      this.validateZip(),
      this.validatePhone1(),
      this.validateEmail(),
      this.validatePrivacyPolicy()
    ];

    for ( var i = 2; i <= 7; i++ ) {
      if ($('lead_gender' + i + '_m').checked || $('lead_gender' + i + '_f').checked ) valid_inputs.push(this.validateInsuredNew(i));
    }
    var valid = $A(valid_inputs).all(function(n) { return n; });
    return valid;
  }
});

HealthForm.addMethods(ValidationHelper);

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