var LifeForm = Class.create();

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

  initializeEvents : function() {
		if ( $('submit') ) {
	    Event.observe('submit', 'click', this.validateFields.bindAsEventListener(this));
		}
	
		/* 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
    });

    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) {
    var form      = new Validator(this.form_elements);
    var is_valid  = form.isFormValid();
		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);
    }
  }
}

if (!(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 6)) {
  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
}
