var LifeForm = Class.create();
LifeForm.prototype =
{
  initialize: function(form_id) {
    this.name           = form_id;
    this.form_elements  = $$(".validation-advice");
    this.initializeEvents();
  },

  initializeEvents : function() {
    // Event.observe(document, 'keypress', this.validateOnReturnKey.bindAsEventListener(this));
    Event.observe('submit', 'click', this.validateFields.bindAsEventListener(this));

    if ($('life_insurance_type')) {
      Event.observe('life_insurance_type', 'change', this.showLengthOfTerm.bindAsEventListener(this));
      this.showLengthOfTerm();
    } 

    if ( $('has_existing_carrier_1') ) {
      Event.observe('has_existing_carrier_1', 'click', this.showExistingCarrier.bindAsEventListener(this));
      Event.observe('has_existing_carrier_0', 'click', this.showExistingCarrier.bindAsEventListener(this));
      this.showExistingCarrier();
    }

    if ( $('has_pre_existing_conditions_1') ) {
      Event.observe('has_pre_existing_conditions_1', 'click', this.showPreExisting.bindAsEventListener(this));
      Event.observe('has_pre_existing_conditions_0', 'click', this.showPreExisting.bindAsEventListener(this));
      this.showPreExisting();
    }
    
    if ( $('takes_medications_1') ) {
      Event.observe('takes_medications_1', 'click', this.showTakesMedications.bindAsEventListener(this));
      Event.observe('takes_medications_0', 'click', this.showTakesMedications.bindAsEventListener(this));
      this.showTakesMedications();
    }
    
    $$(".textfield").each( this.addDefaultValue );

    $$("a.back").each(function(el) {
      Event.observe(el, 'click', function(){window.onbeforeunload=null;});
    });
    
    $$(".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 */
    window.onbeforeunload = this.onUnload;

  },

  onUnload : function() {
    // What?! jQuery from within Prototype? This is crazy I know.
    jQuery.colorbox({
      href:"exit-message.php",
      iframe:true,
      innerWidth:"780px",
      innerHeight: "460px",
      initialWidth:"780px",
      initialHeight: "460px",
      scrolling: false
    });
    // Re-position popup...
    // jQuery("#colorbox").css({ top:jQuery(window).scrollTop() + 75 });

    window.onbeforeunload = null;
    return "Hit CANCEL to get access to rate quotes from leading providers right now.";
  },

  addDefaultValue: function(el) {
    if ($F(el) == '') {
      el.value = el.title;
      el.addClassName("default-text");
    }
  },
  
  removeDefaultValue: function(el) {
    if ($F(el) == el.title) {
      el.value = '';
      el.removeClassName("default-text");
    }
  },

  /***************************************************************************************************
   *show/add functions
   *takes hidden row, element and validation to apply/remove
   */
  showAddValidations: function(name, element, validation_name) {
    var name = String(name);
    $$(name).each(function(element) { element.show(); });
    $(element.id).addClassName(validation_name);
  },

  hideRemoveValidations: function(name, element, validation_name) {
    var name = String(name);
    $$(name).each(function(element) { element.hide(); });
    $(element.id).hide();
    $(element.id).removeClassName(validation_name);
  },

  validateFields: function(e) {
    $$(".textfield").each( this.removeDefaultValue );
    
    var form      = new Validator(this.form_elements);
    var is_valid  = form.isFormValid();

    if ( $("has_pre_existing_conditions_1") && $("has_pre_existing_conditions_1").checked ) {
      if ( !isAnyChecked("pre_existing_conditions_row") ) {
        is_valid  = false;
      }
    }
    
    if ( $("privacy_policy") ) {
      if ( !$("privacy_policy").checked ) {
        is_valid = false;
        $("privacy_policy_error").show();
      } else {
        $("privacy_policy_error").hide();
      }
    }
    
    if (!is_valid) Event.stop(e);
    else window.onbeforeunload = null;
  },

  validateOnReturnKey: function(e) {
    if (e.keyCode == Event.KEY_RETURN) {
      this.validateFields(e);
      Event.stop(e);
    }
  },

  showPreExisting : function() {
    if ($("has_pre_existing_conditions_1").checked) {
      $("pre_existing_conditions_row").show();
    } else {
      $("pre_existing_conditions_row").hide();
      $("pre_existing_conditions_error").removeClassName("validation-advice");
      var PECs = Form.getElements($("pre_existing_conditions_row"));
      PECs.each(function(e) { return (e.checked = false); });
    }
  },

  showTakesMedications : function() {
    if ($("takes_medications_1").checked) {
      this.showAddValidations("#insured1_current_medications_detail_row",$("insured1_current_medications_detail_error"),"required");
    } else {
      this.hideRemoveValidations("#insured1_current_medications_detail_row",$("insured1_current_medications_detail_error"),"required");
      $("insured1_current_medications_detail").clear();
    }
  },

  showExistingCarrier : function() {
    if ( $("has_existing_carrier_1").checked ) {
      this.showAddValidations("#existing_carrier_row",$("existing_carrier_error"),"validate-selected");
    } else {
      this.hideRemoveValidations("#existing_carrier_row",$("existing_carrier_error"),"validate-selected");
      $("existing_carrier").value = "";
    }
  },

  showLengthOfTerm : function() {
    (/(term)/i.test($F("life_insurance_type"))) ? $("length-of-term-field-set").show() : $("length-of-term-field-set").hide();
  }
}

Event.observe(window, 'load', function() {
  var life_form = new LifeForm();
});

function isAnyChecked(parent_id) {
  var is_valid  = true;
  is_valid      =  Form.getElements($(parent_id)).any(function(e) { return (e.checked); });
  if (!is_valid) {
    $("pre_existing_conditions_error").addClassName("validation-advice");
  } else {
    $("pre_existing_conditions_error").removeClassName("validation-advice");
  }
  return is_valid
}