  var HealthForm=Class.create();
  HealthForm.prototype = {
    initialize : function() {
      this.children              = 0;
      this.max_children          = 5;
      this.step                  = 1;
      this.ajax_call_in_progress = false;
      if($F("prefill_zip") != "" && document.getElementById("city_state").length != 0){
				var params = $H({action: 'find_city_from_zip', zip: $F('prefill_zip')});
	      new Ajax.Request('formb_ajax_handler.php', {asynchronous:true,evalScripts:true,method:'post',parameters: params, onComplete: this.onZipValidated.bind(this)});
			}
			
      this.initEvents();
    },
    
    initEvents : function() {
      Event.observe('add-spouse','click', this.onAddSpouse.bindAsEventListener(this));
      Event.observe('add-child','click', this.onAddChild.bindAsEventListener(this));
      Event.observe('done-adding-family','click', this.onDoneAddingFamily.bindAsEventListener(this));
      
      Event.observe(document, 'keypress', this.onInterceptReturns.bindAsEventListener(this));
      Event.observe('prefill_zip','change', this.onChangeZip.bindAsEventListener(this));
    },

    lockEvents : function() {
      this.ajax_call_in_progress = true;
      //alert("Events locked");
      //console.log("Events locked");
    },

    unlockEvents : function() {
      this.ajax_call_in_progress = false;
      //alert("Events unlocked");
      //console.log("Events unlocked");
    },

    eventsLocked : function() {
      return this.ajax_call_in_progress;
    },
    
    onChangeZip : function(e) {
      var params = $H({action: 'find_city_from_zip', zip: $F('prefill_zip')});
      new Ajax.Request('formb_ajax_handler.php', {asynchronous:true,evalScripts:true,method:'post',parameters: params, onComplete: this.onZipValidated.bind(this)});
    },
    
    onZipValidated : function(transport, json) {

      if (json.city) {
        var city_state = json.city + ', ' + json.state;
        this.city  = json.city;
        this.state = json.state;
        this.zip   = json.zip;
        
        $('city_state').update(city_state);
        $('prefill_zip_label').removeClassName('with-errors');
      } else {
        $('city_state').update('');
        $('prefill_zip_label').addClassName('with-errors');
      }
    },
    
    onInterceptReturns : function(e) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }

      if (e.keyCode == Event.KEY_RETURN) {
        if (this.step == 1) {
          this.onDoneAddingFamily(e);
        } else if (this.step == 2) {
          this.onLastStep(e);
        } else if (this.step == 3) {
          this.onGetMyQuote(e);
        } else {
          if (e) Event.stop(e);
        }
        if (e) Event.stop(e);
      }
    },
    
    // Spouse
    onAddSpouse : function(e) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }

      this.showLoading();
      
      new Ajax.Updater('family-list','formb_ajax_handler.php?person=spouse',{asynchronous:true,evalScripts:true,insertion:Insertion.Bottom,onComplete:this.onSpouseAdded.bindAsEventListener(this)});
      this.validateFamily();
      
      if (e) Event.stop(e);
    },
    
    onRemoveSpouse : function(e) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }

      this.showLoading();
      
      Effect.BlindUp($('profile-spouse'),{duration: 0.5, afterFinish: this.onSpouseRemoved.bind(this) });
      $('add-spouse').removeClassName('disabled');
      $('add-spouse').disabled = false;

      if (e) Event.stop(e);
    },
    
    onSpouseRemoved : function(e) {
      $('profile-spouse').remove();
      this.hideLoading();
      this.validateFamily();
    },
    
    onSpouseAdded : function(e) {
      Event.observe('remove-spouse','click', this.onRemoveSpouse.bindAsEventListener(this));
      Effect.BlindDown($('profile-spouse'),{duration:0.5});
      $('add-spouse').addClassName('disabled');
      $('add-spouse').disabled = true;
      this.hideLoading();
    },
    
    // Children
    findLowestChild : function() {
      for (var i = 1; i <= this.max_children; i++) {
        if (!$('profile-child' + i)) return i;
      }
    },
    
    onAddChild : function(e) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }

      this.showLoading();
      
      this.children ++;
      var child_num = this.findLowestChild();
      new Ajax.Updater('family-list','formb_ajax_handler.php?person=child&num=' + child_num,{asynchronous:true,evalScripts:true,insertion:Insertion.Bottom,onComplete:this.onChildAdded.bindAsEventListener(this, child_num)});
      this.validateFamily();
      if (e) Event.stop(e);
    },
    
    onRemoveChild : function(e, child_num) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }

      this.showLoading();
      
      var child_dom_id = 'profile-child' + child_num;
      Effect.BlindUp($(child_dom_id),{duration: 0.5, afterFinish: this.onChildRemoved.bind(this, child_num)});
      
      if (this.children == 5) {
        $('add-child').removeClassName('disabled');
        $('add-child').disabled = false;
      }
      this.children --;
      if (e) Event.stop(e);
    },
    
    onChildRemoved : function(child_num) {
      $('profile-child' + child_num).remove();
      this.hideLoading();
      this.validateFamily();
    },
    
    onChildAdded : function(e, child_num) {
      var child_dom_id = 'profile-child' + child_num;
      Event.observe('remove-child' + child_num, 'click', this.onRemoveChild.bindAsEventListener(this, child_num));
      Effect.BlindDown($(child_dom_id), {duration:0.5});
      
      this.hideLoading();

      if (this.children >= this.max_children) {
        $('add-child').addClassName('disabled');
        $('add-child').disabled = true;
      }
    },
    
    // Done Adding Family
    onDoneAddingFamily : function(e) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }
      this.lockEvents();

      var valid = this.validateFamily();

      if (valid) {
        if ($('step2-wrapper')) {
          this.showLoading();
          this.onShowStep2(e);
          this.hideLoading();
        } else {
          this.showLoading();
          new Ajax.Updater('health-form','formb_ajax_handler.php?step=2',{asynchronous:true,evalScripts:true,insertion:Insertion.Bottom,onComplete:this.onStep2Added.bindAsEventListener(this)});
        }
        changeHeaderMessage(2);
      } else {
        this.unlockEvents();
      }
      
      if(e)Event.stop(e);
    },
    
    onBackToFamily : function(e) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }

      this.showLoading();
      
      Effect.BlindUp($('step2-wrapper'), {duration:0.5, queue: 'start'});
      Effect.BlindDown($('step1-wrapper'), {duration:0.5, queue: 'end'});
      
      this.hideLoading();
      changeHeaderMessage(1);
      this.step = 1;
      if(e) Event.stop(e);
    },
    
    onStep2Added : function(e) {
      Effect.BlindUp($('step1-wrapper'), {duration:0.5, queue: 'start'});
      Effect.BlindDown($('step2-wrapper'), {duration:0.5, queue: 'end'});
      
      //default show/hide
      ($("has_existing_carrier_1").checked) ? $$('.existing_carrier_row').invoke('show') : $$('.existing_carrier_row').invoke('hide');
      ($("takes_medications_1").checked) ? $$('.insured1_current_medications_detail_row').invoke('show') : $$('.insured1_current_medications_detail_row').invoke('hide');
      ($("pre_existing_1").checked) ? $$('.pre_existing_conditions_row').invoke('show') : $$('.pre_existing_conditions_row').invoke('hide');

      // Navigation
      Event.observe('back-to-family','click', this.onBackToFamily.bindAsEventListener(this));
      Event.observe('last-step','click', this.onLastStep.bindAsEventListener(this));

      Event.observe('has_existing_carrier_0', 'click', function() {
        $$('.existing_carrier_row').invoke('hide');
      });

      Event.observe('has_existing_carrier_1', 'click', function() {
        $$('.existing_carrier_row').invoke('show');
      });

      Event.observe('takes_medications_0', 'click', function() {
        $$('.insured1_current_medications_detail_row').invoke('hide');
      });

      Event.observe('takes_medications_1', 'click', function() {
        $$('.insured1_current_medications_detail_row').invoke('show');
      });

      Event.observe('pre_existing_0', 'click', function() {
        $$('.pre_existing_conditions_row').invoke('hide');
      });

      Event.observe('pre_existing_1', 'click', function() {
        $$('.pre_existing_conditions_row').invoke('show');
      });
      
      this.hideLoading();
      this.step = 2;
      window.setTimeout(this.focusStep2, 1500);
    },

    focusStep2 : function() {
      //alert( "here we are");
      $('has_existing_carrier_0').focus();
    },
    
    onShowStep2 : function() {
      Effect.BlindUp($('step1-wrapper'), { duration:0.5, queue: 'start' });
      Effect.BlindDown($('step2-wrapper'), { duration:0.5, queue: 'end' });
      this.step = 2;
      changeHeaderMessage(2);
    },

    onLastStep : function(e) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }
      this.lockEvents();

      var valid = this.validateStep2();

      if (valid) {

        if ($('step3-wrapper')) {
          this.showLoading();
          this.onShowStep3(e);
          this.hideLoading();
        } else {
          this.showLoading();
          new Ajax.Updater('health-form','formb_ajax_handler.php?step=3',{asynchronous:true,evalScripts:true,insertion:Insertion.Bottom,onComplete:this.onStep3Added.bindAsEventListener(this)});
        }
				changeHeaderMessage(3);
      } else {
        this.unlockEvents();
      }
      
      if(e)Event.stop(e);
    },
    
    onStep3Added : function(e) {
      Effect.BlindUp($('step2-wrapper'), {duration:0.5, queue: 'start'});
      Effect.BlindDown($('step3-wrapper'), {duration:0.5, queue: 'end'});

      if (this.city) $('address1_city').value = this.city;
      if (this.state) $('address1_state').value = this.state;
      if (this.zip) $('address1_zip').value = this.zip;

      Event.observe('back-to-step-2','click', this.onBackToStep2.bindAsEventListener(this));
      Event.observe('get-my-quote','click', this.onGetMyQuote.bindAsEventListener(this));
      this.step = 3;
      window.setTimeout(this.focusStep3, 1500);

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

    focusStep3 : function() {
      $('first_name').focus();
    },
    
    onShowStep3 : function() {
      Effect.BlindUp($('step2-wrapper'), {duration:0.5, queue: 'start'});
      Effect.BlindDown($('step3-wrapper'), {duration:0.5, queue: 'end'});
      this.step = 3;
      changeHeaderMessage(3);
    },
    
    onBackToStep2 : function(e) {
      this.showLoading();
      Effect.BlindUp($('step3-wrapper'), {duration:0.5, queue: 'start'});
      Effect.BlindDown($('step2-wrapper'), {duration:0.5, queue: 'end'}); 
      changeHeaderMessage(2);
      this.step = 2;
      this.hideLoading();
      if(e) Event.stop(e);
    },
    
    onGetMyQuote : function(e) {
      if (this.eventsLocked()) {
        if (e) Event.stop(e);
        return false;
      }

      var valid = this.validateContactInfo();

      if (valid) {
      } else {
        if(e)Event.stop(e);
      }
    },

    // Validations
    validateFamily : function() {
      var valid_inputs = [];
      for (var i = 1; i <= this.children + 2; i++) {
        if ($('gender' + i)) valid_inputs.push(this.validateInsured(i));
      }
      
      return $A(valid_inputs).all(function(n) { return n; });
    },
    
    validateContactInfo : function() {
      var valid_inputs = [
        this.validateFirstName(),
        this.validateLastName(),
        this.validateAddressLine1(),
        this.validateCity(),
        this.validateState(),
        this.validateZip(),
        this.validatePhone1(),
        this.validatePhone2(),
        this.validateEmail(),
        this.validatePrivacyPolicy()
      ];
      
      var valid = $A(valid_inputs).all(function(n) { return n; });
      if (!valid) {
        $('step3').addClassName('contains-errors');
        $('advice-step3').show();
      } else {
        $('step3').removeClassName('contains-errors');
        $('advice-step3').hide();
      }
      
      return valid;
    },
    
    validateInsured : function(num) {
      var valid = true;
      if(num <= 2){
	      var valid_inputs = [
	        this.validateGender(num),
	        this.validateHeight(num),
	        this.validateWeight(num),
	        this.validateDateOfBirth(num)
	      ];
			}else{
	      var valid_inputs = [
	        this.validateGender(num),
	        this.validateHeight(num),
	        this.validateWeight(num),
	        this.validateChildDateOfBirth(num)
	      ];			
			}
      var profile = this.getInsuredDomId(num);
      var valid   = $A(valid_inputs).all(function(n) { return n; });
            
      if (!valid) {
        $(profile).addClassName('contains-errors');
        $('advice-insured' + num).show();
      } else {
        $(profile).removeClassName('contains-errors');
        $('advice-insured' + num).hide();
      }
      
      return valid;
    },

    validateStep2 : function() {
      var valid_inputs = [
        this.validateCurrentlyInsured(),
        this.validateCoverageStartDate(),
        this.validateMedications(),
        this.validatePreExistingConditions()
      ];
      
      var valid = $A(valid_inputs).all(function(n) { return n; });

      if (!valid) {
        $('step2').addClassName('contains-errors');
        $('advice-step2').show();
      } else {
        $('step2').removeClassName('contains-errors');
        $('advice-step2').hide();
      }

      return valid;
    },

    validateCurrentlyInsured : function() {
	    var valid = true;
	    if ($F('has_existing_carrier_1')) {
		    valid =  $('existing_carrier').selectedIndex > 0;
	    }
	
      if (!valid) {
        $('existing_carrier_label').addClassName('with-errors');
        $('existing_carrier_label').title = "Please select a carrier";
      } else {
        $('existing_carrier_label').removeClassName('with-errors');
        $('existing_carrier_label').title = "";
      }
	
	    return valid;
    },

    validateCoverageStartDate : function() {
	    var valid = true;
		  valid =  Validation.get('validate-coverage-start-date').test($F('reqdate_mm_begin'),$('reqdate_mm_begin'));
	
      if (!valid) {
        $('reqdate_begin_label').addClassName('with-errors');
        $('reqdate_begin_label').title = "Please select a valid future date";
        $('reqdate_begin_error').show();
      } else {
        $('reqdate_begin_label').removeClassName('with-errors');
        $('reqdate_begin_label').title = "";
        $('reqdate_begin_error').hide();
      }
	
	    return valid;
    },
    
    validateMedications : function() {
	    var valid = true;
	    if ($F('takes_medications_1')) {
		    valid =  Validation.get('required').test($F('insured1_current_medications_detail'));
	    }
	
      if (!valid) {
        $('insured1_current_medications_detail_label').addClassName('with-errors');
        $('insured1_current_medications_detail_label').title = "Please list the medications you take";
      } else {
        $('insured1_current_medications_detail_label').removeClassName('with-errors');
        $('insured1_current_medications_detail_label').title = "";
      }

	    return valid;
    },

    validatePreExistingConditions : function() {
	    var valid = true;
	    if ($F('pre_existing_1')) {
		    var conditions = $('pre_existing_conditions').getElementsByTagName('INPUT');
		    valid =  $A(conditions).any(function(n) { return $F(n) != null; });
	    }
	
      if (!valid) {
        $('pre_existing_conditions_label').addClassName('with-errors');
        $('pre_existing_conditions_label').title = "Please select at least one pre existing condition";
      } else {
        $('pre_existing_conditions_label').removeClassName('with-errors');
        $('pre_existing_conditions_label').title = "";
      }
	
	    return valid;
    },
    
    validateGender : function(num) {
      var valid = Validation.get('validate-selection').test($F('gender' + num), $('gender' + num));
      if (!valid) {
        $('gender' + num + '_label').addClassName('with-errors');
        $('gender' + num + '_label').title = "Please enter a valid gender";
      } else {
        $('gender' + num + '_label').removeClassName('with-errors');
        $('gender' + num + '_label').title = "";
      }
      
      return valid;
    },
    
    validateHeight : function(num) {
      var valid = Validation.get('validate-all-selection').test($F('insured' + num + '_height_inches'), $('insured' + num + '_height_inches'));
      if (!valid) {
        $('insured' + num + '_height_label').addClassName('with-errors');
        $('insured' + num + '_height_label').title = "Please enter a valid height";
      } else {
        $('insured' + num + '_height_label').removeClassName('with-errors');
        $('insured' + num + '_height_label').title = "";
      }
      
      return valid;
    },
    
    validateWeight : function(num) {
      var valid = Validation.get('validate-weight').test($F('insured' + num + '_weight'));
      if (!valid) {
        $('insured' + num + '_weight_label').addClassName('with-errors');
        $('insured' + num + '_weight_label').title = "Please enter a valid weight";
      } else {
        $('insured' + num + '_weight_label').removeClassName('with-errors');
        $('insured' + num + '_weight_label').title = "";
      }
      
      return valid;
    },
    
    validateDateOfBirth : function(num) {
      var valid = Validation.get('validate-three-part-dob').test($F('dob' + num + '_yyyy_on'), $('dob' + num + '_yyyy_on'));
      if (!valid) {
        $('dob' + num + '_label').addClassName('with-errors');
        $('dob' + num + '_label').title = "Please enter a valid date of birth";
      } else {
        $('dob' + num + '_label').removeClassName('with-errors');
        $('dob' + num + '_label').title = "";
      }
      
      return valid;
    },
    
    validateChildDateOfBirth : function(num) {
      var valid = Validation.get('validate-three-part-child-dob').test($F('dob' + num + '_yyyy_on'), $('dob' + num + '_yyyy_on'));
      if (!valid) {
        $('dob' + num + '_label').addClassName('with-errors');
        $('dob' + num + '_label').title = "Please enter a valid date of birth";
      } else {
        $('dob' + num + '_label').removeClassName('with-errors');
        $('dob' + num + '_label').title = "";
      }
      
      return valid;
    },
    
    validateFirstName : function() {
      var valid = Validation.get('validate-name').test($F('first_name'));
      if (!valid) {
        $('first_name_label').addClassName('with-errors');
        $('first_name_label').title = "Please enter a first name (letters only please)";
      } else {
        $('first_name_label').removeClassName('with-errors');
        $('first_name_label').title = "";
      }
      
      return valid;
    },
    
    validateLastName : function() {
      var valid = Validation.get('validate-name').test($F('last_name'));
      if (!valid) {
        $('last_name_label').addClassName('with-errors');
        $('last_name_label').title = "Please enter a last name (letters only please)";
      } else {
        $('last_name_label').removeClassName('with-errors');
        $('last_name_label').title = "";
      }
      
      return valid;
    },
    
    validateAddressLine1 : function() {
      var valid = Validation.get('required').test($F('address1_street1'));
      if (!valid) {
        $('address1_street1_label').addClassName('with-errors');
        $('address1_street1_label').title = "Please enter a street address";
      } else {
        $('address1_street1_label').removeClassName('with-errors');
        $('address1_street1_label').title = "";
      }
      
      return valid;
    },
    
    validateCity : function() {
      var valid = Validation.get('required').test($F('address1_city'));
      if (!valid) {
        $('address1_city_label').addClassName('with-errors');
        $('address1_city_label').title = "Please enter a city";
      } else {
        $('address1_city_label').removeClassName('with-errors');
        $('address1_city_label').title = "";
      }
      
      return valid;
    },
    
    validateState : function() {
      var valid = Validation.get('validate-selection').test($F('address1_state'), $('address1_state'));
      if (!valid) {
        $('address1_state_label').addClassName('with-errors');
        $('address1_state_label').title = "Please select a state";
      } else {
        $('address1_state_label').removeClassName('with-errors');
        $('address1_state_label').title = "";
      }
      
      return valid;
    },
    
    validateZip : function() {
      var valid = Validation.get('validate-zip').test($F('address1_zip'));
      if (!valid) {
        $('address1_zip_label').addClassName('with-errors');
        $('address1_zip_label').title = "Please enter a valid zip";
      } else {
        $('address1_zip_label').removeClassName('with-errors');
        $('address1_zip_label').title = "";
      }
      
      return valid;
    },
    
    validatePhone : function(num) {
      var phone_number = $F('phone' + num + '_area') + $F('phone' + num + '_exchange') + $F('phone' + num + '_station');
      var phone_label  = $('phone' + num + '_label');
      var valid        = Validation.get('validate-mandatory-phone').test(phone_number);
      
      if (!valid) {
        phone_label.addClassName('with-errors');
        phone_label.title = "Please enter a valid phone number";
      } else {
        phone_label.removeClassName('with-errors');
        phone_label.title = "";
      }
      
      return valid;
    },
    
    validatePhone1 : function() {
      return this.validatePhone(1);
    },
    
    validatePhone2 : function() {
      return this.validatePhone(2);
    },
    
    validateEmail : function() {
      var valid = Validation.get('validate-mandatory-email').test($F('email1'));
      if (!valid) {
        $('email1_label').addClassName('with-errors');
        $('email1_label').title = "Please enter a valid email";
      } else {
        $('email1_label').removeClassName('with-errors');
        $('email1_label').title = "";
      }
      
      return valid;
    },
    
    validatePrivacyPolicy : function() {
      var valid = Validation.get('validate-checked').test($F('privacy_policy'));
      if (!valid) {
        $('privacy_policy').up().addClassName('with-errors');
      } else {
        $('privacy_policy').up().removeClassName('with-errors');
      }
      
      return valid;
    },
    
    getInsuredDomId : function(num) {
      if (num == 1) {
        return 'profile-you';
      } else if (num == 2) {
        return 'profile-spouse';
      } else {
        return 'profile-child' + (num - 2);
      }
    },
    
    showLoading : function() {
      $('ajax-loader-img').show();
      if (!this.eventsLocked()) this.lockEvents();
    },
    
    hideLoading : function() {
      $('ajax-loader-img').hide();
      this.unlockEvents();
    }
  }

function changeHeaderMessage(step){
  if(step == 2){
  	$("step_header_message").innerHTML = "Step " + step + " - Health Information";
  }else if(step == 3){
  	$("step_header_message").innerHTML = "Step " + step + " - Contact Information";
  }else{
		$("step_header_message").innerHTML = "Step " + step + " - Get Started";
	}
}

if (!(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 6)) {
  Event.observe(window, 'load', function() {
    var health_form = new HealthForm();
  });
}
