var HealthForm = Class.create();
HealthForm.prototype =
{
	initialize: function(form_id){

	  if ( $("health-info") ) {
  		this.initializeHealthDisplay();
  		this.initializeRequiredHealthFields();
  		this.initializeHealthEvents();

        /* Handle window closing */
        window.onbeforeunload = this.onUnload;
	  }
		
	  if ( $("senior-health-info") ) {
  		this.initializeRequiredSeniorFields();
  	}
		
		this.lockReturnKey = false;
		this.form_elements = this.getErrorElements();
		this.step          = 1;
		this.is_valid      = true;
	},

	/***************************************************************************************************
	 *initialize the elements of the form, hide and show as directed
	 */
	initializeHealthDisplay : function(){
		showChildren($("number_of_children"));
		showSpouse();
		
		$("additional-family").show();
		this.showExistingCarrier();
		this.showTakesMedications();
		this.showPreExisting();
	},

	/*************************************************
	 *initialize the validations for required elements
	 */
	initializeRequiredHealthFields : function() {
		// coverage section (applicant)
		$("gender1_error").addClassName("required");
		$("dob1_on_error").addClassName("validate-dob");
		$("insured1_height_error").addClassName("validate-height");
		$("insured1_weight_error").addClassName("validate-weight");
		
		// health info section
		$("reqdate_begin_error").addClassName("validate-request-date");
		
		// contact info section
		$("first_name_error").addClassName("validate-alpha");
		$("last_name_error").addClassName("validate-alpha");
		$("address1_street1_error").addClassName("required");
		$("address1_city_error").addClassName("validate-alpha");
	
    if ( $("address1_state_error") ) {
    	$("address1_state_error").addClassName("validate-state");
    }
  
    if ( $("address1_zip_error") ) {
    	$("address1_zip_error").addClassName("validate-zip");
    }
  
		$("phone1_error").addClassName("validate-phone");
		$("email1_error").addClassName("validate-email");
		$("privacy_policy_error").addClassName("validate-privacy");	    		
	},
	
	initializeRequiredSeniorFields : function() {
    if ( $("has_medicare_a_b_error") ) $("has_medicare_a_b_error").addClassName("validate-one-selected");
    if ( $("has_esrd_error") ) $("has_esrd_error").addClassName("validate-one-selected");
	},

	/***************************************************************************************************
	 *add event listeners for submit button, return key and custom onclick/onchange
	 */
	initializeHealthEvents : function(){
		Event.observe(document, "keypress", this.validateOnReturnKey.bindAsEventListener(this));
		Event.observe("submit", "click", this.validateFields.bindAsEventListener(this));
					
		Event.observe("takes_medications_1", "click", this.showTakesMedications.bindAsEventListener(this));
		Event.observe("takes_medications_0", "click", this.showTakesMedications.bindAsEventListener(this));

		Event.observe("pre_existing_1", "click", this.showPreExisting.bindAsEventListener(this));
		Event.observe("pre_existing_0", "click", this.showPreExisting.bindAsEventListener(this));

		Event.observe("has_existing_carrier_1", "click", this.showExistingCarrier.bindAsEventListener(this));
		Event.observe("has_existing_carrier_0", "click", this.showExistingCarrier.bindAsEventListener(this));
		
		Event.observe("add-spouse", "click", function(e){
			$("has_spouse").value	=	1;
			showSpouse();
			spouseValidation(true);
			Event.stop(e);
		});
		
		Event.observe("remove-spouse", "click", function(e){
			$("has_spouse").value	=	0;
			showSpouse();
			spouseValidation(false);
			Event.stop(e);
		});
		
		Event.observe("add-child", "click", function(e){
			var children	=	$F("number_of_children");
			if(children < 5){
				$("number_of_children").value =	parseInt($F("number_of_children")) + 1;
				showChildren($("number_of_children"));
			}
			Event.stop(e);
		});
		
		Event.observe("remove-child1", "click", function(e){
			$("child_option1").hide();
			toggleAddChild();
			changeValidationForInsured(3, false);
			shiftChildren(3);
			Event.stop(e);
		});
		
		Event.observe("remove-child2", "click", function(e){
			$("child_option2").hide();
			toggleAddChild();
			changeValidationForInsured(4, false);
			shiftChildren(4);
			Event.stop(e);
		});
		
		Event.observe("remove-child3", "click", function(e){
			$("child_option3").hide();
			toggleAddChild();
			changeValidationForInsured(5, false);
			shiftChildren(5);
			Event.stop(e);
		});
		
		Event.observe("remove-child4", "click", function(e){
			$("child_option4").hide();
			toggleAddChild();
			changeValidationForInsured(6, false);
			shiftChildren(6);
			Event.stop(e);
		});
		
		Event.observe("remove-child5", "click", function(e){
			$("child_option5").hide();
			toggleAddChild();
			changeValidationForInsured(7, false);
			shiftChildren(7);
			Event.stop(e);
		});
	},

	/***************************************************************************************************
	 *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){
		this.form_elements	= $$(".error");
		var form						= new Validator(this.form_elements);
		this.is_valid 			= form.isFormValid();

		if($("pre_existing_1").checked){
			if(!isAnyChecked("pre_existing_conditions_row")){
				this.is_valid	= false;
			}
		}

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

	validateOnReturnKey: function(e){
		if(e.keyCode == Event.KEY_RETURN){
			this.validateFields(e);
			Event.stop(e);
		}
	},
	
	getErrorElements: function(){
		return $$("error");
	},

	/***************************************************************************************************
	 *Custom functions
	 */

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

	showPreExisting : function(){
		if($("pre_existing_1").checked){
			$("pre_existing_conditions_row").show();
		}else{
			$("pre_existing_conditions_row").hide();
			var PECs = Form.getElements($("pre_existing_conditions_row"));
			PECs.each(function(e){ return (e.checked = false); });
		}
	},

	showExistingCarrier : function(){
		($("has_existing_carrier_1").checked) ? this.showAddValidations("#existing_carrier_row",$("existing_carrier_error"),"required") : this.hideRemoveValidations("#existing_carrier_row",$("existing_carrier_error"),"required");
	},
	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() + 45 });

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


function spouseValidation(validate){
	if(validate){
		$("gender2_error").addClassName("required");
		$("dob2_on_error").addClassName("validate-dob");
		$("insured2_height_error").addClassName("validate-height");
		$("insured2_weight_error").addClassName("validate-weight");
	}else{
		$("gender2_error").removeClassName("required");
		$("dob2_on_error").removeClassName("validate-dob");
		$("insured2_height_error").removeClassName("validate-height");
		$("insured2_weight_error").removeClassName("validate-weight");
		clearErrorMessage("gender2_error");
		clearErrorMessage("dob2_on_error");
		clearErrorMessage("insured2_height_error");
		clearErrorMessage("insured2_weight_error");
		$("dob2_mm_on").clear();
		$("dob2_dd_on").clear();
		$("dob2_yyyy_on").clear();
		$("insured2_height_feet").clear();
		$("insured2_height_inches").clear();
		$("insured2_weight").clear();
	}
}

function isEmptyInsured(insured){
	var gender 	= isEmptyGender(insured);
	var dob 		= isEmptyDob(insured);
	var height 	= isEmptyHeight(insured);
	var weight 	= isEmptyWeight(insured);
	return (gender && dob && height && weight);
}

function isEmptyGender(insured){
	return (($F("gender" + insured) == ""));
}

function isEmptyDob(insured){
	return (($F("dob" + insured + "_mm_on") == "") && ($F("dob" + insured + "_dd_on") == "") && ($F("dob" + insured + "_yyyy_on") == ""));
}

function isEmptyHeight(insured){
	return (($F("insured" + insured + "_height_feet") == ""));
}

function isEmptyWeight(insured){
	return (($F("insured" + insured + "_weight") == ""));
}

function showSpouse(){
	if($F("has_spouse") == 1){
		$("add-spouse").hide();
		$("disabled-spouse").show();
		$("spouse-row").show();
		spouseValidation();
	}else{
		$("add-spouse").show();
		$("disabled-spouse").hide();
		$("spouse-row").hide();
		spouseValidation();
	}
}

function showChildren(el) {
	var num_children = $F(el);

	for (var i = 1;i <= 5; i++) {
		var id			= "child_option" + i;
		var insured = i + 2;

		if ( i <= num_children ) {
			$(id).show();
			$("child" + i).show();
			changeValidationForInsured(insured, true);
		} else {
			$(id).hide();
			$("gender" + insured).value = "";
			changeValidationForInsured(insured, false);
		}
	}
	toggleAddChild();
}

function toggleAddChild(){
	var num_children	=	$F("number_of_children");
	if(num_children == 5){
		$("disabled-child").show();
		$("add-child").hide();
	}else{
		$("disabled-child").hide();
		$("add-child").show();
	}
}

function shiftChildren(child_removed){
	var packed_children	=	new Array();
	var insured_kid			=	3;
	var total_children	=	0;
	var start_total			=	$F("number_of_children");
	
	//Shift children down
	for (i=3; i<=7; i++) {
			if(
					$F("gender" +1) != "" && $F("insured" +  i + "_height_feet") != "" && $F("insured" +  i + "_height_inches") != "" &&
					$F("dob" +  i + "_yyyy_on") != "" && $F("dob" +  i + "_mm_on") != "" && $F("dob" +  i + "_dd_on") != ""
				){						
				if(i < child_removed){
					packed_children["gender" + insured_kid]											=	$F("gender" + i);
					packed_children["insured" + insured_kid + "_height_feet"]		=	$F("insured" +  i + "_height_feet");
					packed_children["insured" + insured_kid + "_height_inches"]	=	$F("insured" +  i + "_height_inches");
					packed_children["insured" + insured_kid + "_weight"]				=	$F("insured" +  i + "_weight");
					packed_children["is_smoker" + insured_kid + "_1"]						=	$("is_smoker" +  i + "_1").checked;
					packed_children["is_student" + insured_kid + "_1"]					=	$("is_student" +  i + "_1").checked;
					packed_children["dob" + insured_kid + "_yyyy_on"]						=	$F("dob" +  i + "_yyyy_on");
					packed_children["dob" + insured_kid + "_mm_on"]							=	$F("dob" +  i + "_mm_on");
					packed_children["dob" + insured_kid + "_dd_on"]							=	$F("dob" +  i + "_dd_on");
					insured_kid++;
				}else if (i > child_removed){
					if($F("gender" + i) != ""){
						packed_children["gender" + insured_kid]											=	$F("gender" + i);
						packed_children["insured" + insured_kid + "_height_feet"]		=	$F("insured" +  i + "_height_feet");
						packed_children["insured" + insured_kid + "_height_inches"]	=	$F("insured" +  i + "_height_inches");
						packed_children["insured" + insured_kid + "_weight"]				=	$F("insured" +  i + "_weight");
						packed_children["is_smoker" + insured_kid + "_1"]						=	$("is_smoker" +  i + "_1").checked;
						packed_children["is_student" + insured_kid + "_1"]					=	$("is_student" +  i + "_1").checked;
						packed_children["dob" + insured_kid + "_yyyy_on"]						=	$F("dob" +  i + "_yyyy_on");
						packed_children["dob" + insured_kid + "_mm_on"]							=	$F("dob" +  i + "_mm_on");
						packed_children["dob" + insured_kid + "_dd_on"]							=	$F("dob" +  i + "_dd_on");
						insured_kid++;
					}
				}
			}
		}
		
		for (i=3; i<=7; i++) {
			if(i < insured_kid){
				$("insured" +  i + "_height_feet").value	 									= packed_children["insured" +  i + "_height_feet"];
				$("insured" +  i + "_height_inches").value 									= packed_children["insured" +  i + "_height_inches"];
				$("insured" +  i + "_weight").value													= packed_children["insured" +  i + "_weight"];
				$("gender" +  i + "").value																	= packed_children["gender" +  i + ""];
				$("is_smoker" +  i + "_1").checked						 							= packed_children["is_smoker" +  i + "_1"];
				$("is_student" +  i + "_1").checked													= packed_children["is_student" +  i + "_1"];
				$("dob" +  i + "_yyyy_on").value														= packed_children["dob" +  i + "_yyyy_on"];
				$("dob" +  i + "_mm_on").value															= packed_children["dob" +  i + "_mm_on"];
				$("dob" +  i + "_dd_on").value															= packed_children["dob" +  i + "_dd_on"];
			}else{
				if(packed_children["gender" + i] != undefined){
					changeValidationForInsured(i, false);
				}
			}
		}
		
		$("number_of_children").value	=	start_total - 1;
		showChildren($("number_of_children"))
}

function changeValidationForInsured(insured, add_validations) {
	var id			= "gender" + insured;
	var gender	= $F(id);

	if ( add_validations ) {
		$(id + "_error").addClassName("required");
		$("insured" + insured + "_height_error").addClassName("validate-height");
		$("insured" + insured + "_weight_error").addClassName("validate-weight");
		$("dob" + insured + "_on_error").addClassName("validate-child-dob");
	} else {
		$(id).clear();
		$("insured" + insured + "_height_feet").clear();
		$("insured" + insured + "_height_inches").clear();
		$("insured" + insured + "_weight").value	=	"";
		$("dob" + insured + "_mm_on").value	=	"";
		$("dob" + insured + "_dd_on").value	=	"";
		$("dob" + insured + "_yyyy_on").value	=	"";
		$(id + "_error").removeClassName("required");
		$("insured" + insured + "_height_error").removeClassName("validate-height");
		$("insured" + insured + "_weight_error").removeClassName("validate-weight");
		$("dob" + insured + "_on_error").removeClassName("validate-child-dob");
		$(id + "_error").hide();
		$("insured" + insured + "_height_error").hide();
		$("insured" + insured + "_weight_error").hide();
		$("dob" + insured + "_on_error").hide();
	}
}

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("error");
	}else{
		$("pre_existing_conditions_error").removeClassName("error");
	}
	return is_valid
}

if (!(BrowserDetect.browser == "Explorer" && BrowserDetect.version < 6)) {
	FastInit.addOnLoad(function() {
		var health_form = new HealthForm();
	});
}
