/*
Global Regexes for field validation
*/
var validation_regex = new Array();
validation_regex['email'] = /^(([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)$/;
validation_regex['phone'] = /^[0-9.,-_\s]{7,}$/;
validation_regex['fax'] = /^[0-9.,-_\s]{7,}$/;


var validation_messages = new Array();
validation_messages['email'] = "Please enter a valid email."; 
validation_messages['phone'] = "Please enter a valid phone number.";
validation_messages['fax'] = "Please enter a valid fax number.";
validation_messages['password'] = "The password fields do not match.";

var highlight_color = "#e80000";
var default_color = "#6d6864";

/*
This looks for inputs and selects that have a class of the format: required_xx or required_validationtype_xx.
Having found one, it finds the label with the same class name and 
colors it the highlighted color if that input did not validate
*/

function validate_forms() {

	//settings
	var highlight_color = "#e80000";
	var default_color = "#6d6864";
	var error_title = "Required Fields Missing";
	var error_msg = "Please fill in all required fields.<br>\n";

	//local variables	
	var input_array	= document.getElementsByTagName("input");//get all the input elements
	var select_array = document.getElementsByTagName("select");
	var textarea_array = document.getElementsByTagName("textarea");
	input_array = combine_arrays(input_array, select_array);
	input_array = combine_arrays(input_array, textarea_array);
	var valid_item;
	var valid_form = true;
	var input;
	var label;
	var temp_array;
	var validation_filter;
	var parameters;
	var passwords = new Array();
	var good_labels = new Array();
	var bad_labels = new Array();
	var class_name;
	
	//loop through each div, checking if it is required
	for( i = 0; i < input_array.length; i++ ) {
			if(input_array[i].className.indexOf("required_") != -1) {
	
				class_name = strip_nonrequired_class_names(input_array[i].className);
				
				valid_item = true;
				parameters = class_name.split("_");
				
				//grab the corresponding label
				label = getLabelName(class_name);
				
				//special case for passwords
				if( parameters.length == 3 && parameters[1] == 'password' ) {
					//first time we've seen this numbered password	
					if ( !has_index(passwords, parameters[2]) ){
						passwords[parameters[2]] = input_array[i].value;
					}
					//second time
					else {
						//they match and aren't blank
						if (passwords[parameters[2]] == input_array[i].value &&	input_array[i].value != "") {
							color_labels(class_name, default_color);
						} else {
						//they don't match so color them
							color_labels(class_name, highlight_color);
							valid_item = false;
							error_msg += validation_messages['password'] + "<br>\n";
						}
					}
				}

				//figure out type of validation (classes should be named: required_typeofvalidation_number, or required_number)
				//example: required_email_01, or required_01
				if( parameters.length == 3) {
					validation_filter = validation_regex[parameters[1]];	
					if (validation_filter && !validation_filter.test(input_array[i].value)) {
						valid_item = false;	
						//don't put in an error message twice
						if(error_msg.indexOf(validation_messages[parameters[1]]) == -1) {
							error_msg += validation_messages[parameters[1]] + "<br>\n";
						}
					}
				}
				
				if ( input_array[i].type == "checkbox" ) {
					if(!input_array[i].checked) {
						valid_item = false;
					}
				}
				
				if ( input_array[i].type == "radio" ) {
					radioBtn = document.getElementsByName(input_array[i].name);
					if(radioBtn[0].name != "change_reason") {
						var checked = false;
						for (var x=radioBtn.length-1; x > -1; x--) {
							if(radioBtn[x].checked) {
								checked = true;
							}
						}
						if(!checked) {
							valid_item = false;
						}
					} else {
						cancelCobra = document.getElementsByName("cobra");
						addressType = document.getElementsByName("address_type");
						
						if( addressType[0].checked == false && cancelCobra[2].checked == false ) {
							var checked = false;
							for (var x=radioBtn.length-1; x > -1; x--) {
								if(radioBtn[x].checked) {
									checked = true;
								}
							}
							if(!checked) {
								valid_item = false;
							}
						}
					}
				}
				
				if (input_array[i].id == "social_security_number") {
					if(!(input_array[i].value.match(/^[0-9]{3,3}[-\ ][0-9]{2,2}[-\ ][0-9]{4,4}$/) || input_array[i].value.match(/^[0-9]{9,9}$/))) {
						error_msg += "Please enter a valid social security number.<br>\n";
						valid_item = false;
					}
				}
				//check if the field is blank
				if (input_array[i].value == "" || input_array[i].value == "00") {
					//alert(input_array[i].name);
					valid_item = false;
				}

				//color the label if it's not valid
				if ( !valid_item ) {
					label.style.color = highlight_color;	
					valid_form = false; //if any of the items were invalid, the whole form is invalid

					//this is for labels that correspond to multiple inputs, such as dates
					bad_labels.push(label);
				} else {
					label.style.color = default_color;

					//this is for labels that correspond to multiple inputs, such as dates
					good_labels.push(label);
				}
			}
	}
	
	//custom checking for the online change form please forgive me for not doing this better jk
	if( document.forms[0].name == "online_change_form") {
		cobra = document.getElementsByName("cobra");
		if(cobra[0].checked || cobra[1].checked || cobra[2].checked) {
			month = document.getElementsByName("cobra_date[month]");
			day = document.getElementsByName("cobra_date[day]");
			year = document.getElementsByName("cobra_date[year]");
			label = getLabelName("required_cobra_date");
			if(month[0].value == "" || day[0].value == "" || year[0].value == "") {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
		}
		
		//Cobra state continuation
		curElement = document.getElementsByName("cobra_cont_months");
		if(curElement[0].value != "") {
			month = document.getElementsByName("cobra_date1[month]");
			day = document.getElementsByName("cobra_date1[day]");
			year = document.getElementsByName("cobra_date1[year]");
			label = getLabelName("required_cobra_date1");
			if(month[0].value == "" || day[0].value == "" || year[0].value == "") {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
		}
		
		//start spouse
		curRadio = document.getElementsByName("spouse_change");
		if(curRadio[0].checked || curRadio[1].checked) {
			var spouseA = new Array("spouse_last_name","spouse_first_name");
			for(var i=0; i < spouseA.length; i++) {
				if(checkIfEmpty(spouseA[i]) == false) {
					valid_form = false;
				}
			}
			relRadio = document.getElementsByName("spouse_relationship");
			label = getLabelName("required_spouse_relationship");
			if(relRadio[0].checked == false && relRadio[1].checked == false) {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
			month = document.getElementsByName("spouse_birthday[month]");
			day = document.getElementsByName("spouse_birthday[day]");
			year = document.getElementsByName("spouse_birthday[year]");
			label = getLabelName("required_spouse_birthday");
			if(month[0].value == "" || day[0].value == "" || year[0].value == "") {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
		}
		//Plan Change
		curRadio = document.getElementsByName("plan_change");
		label = getLabelName("required_change_date");
		if(curRadio[0].checked) {
			month = document.getElementsByName("change_date[month]");
			day = document.getElementsByName("change_date[day]");
			year = document.getElementsByName("change_date[year]");
			if(month[0].value == "" || day[0].value == "" || year[0].value == "") {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
		} else {
			good_labels.push(label);
		}
		//Cancel Entire Policy
		label = getLabelName("required_cancel_date");
		if(curRadio[1].checked) {
			month = document.getElementsByName("cancel_date[month]");
			day = document.getElementsByName("cancel_date[day]");
			year = document.getElementsByName("cancel_date[year]");
			if(month[0].value == "" || day[0].value == "" || year[0].value == "") {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
		} else {
			good_labels.push(label);
		}
		//Delete/Add ONLY dependants listed below
		label = getLabelName("required_change_dependents_date");
		if(curRadio[2].checked) {
			month = document.getElementsByName("change_dependents_date[month]");
			day = document.getElementsByName("change_dependents_date[day]");
			year = document.getElementsByName("change_dependents_date[year]");
			if(month[0].value == "" || day[0].value == "" || year[0].value == "") {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
		} else {
			good_labels.push(label);
		}
		
		//start reason
		curRadio = document.getElementsByName("change_reason");
		
		cancelCobra = document.getElementsByName("cobra");
		addressType = document.getElementsByName("address_type");
		
		//alert(addressType[0].checked);
		//alert(cancelCobra[2].checked);
		
		if( addressType[0].checked == false && cancelCobra[2].checked == false ) {
			//Removed per DS request, used for other text explanation
			/*label = getLabelName("required_explanation");
			element = document.getElementsByName("explanation");
			if(element[0].value == "" && curRadio[10].checked) {
				bad_labels.push(label);
				valid_form = false;
			} else {
				good_labels.push(label);
			}*/
			
			month = document.getElementsByName("last_day_emp[month]");
			day = document.getElementsByName("last_day_emp[day]");
			year = document.getElementsByName("last_day_emp[year]");
			label = getLabelName("required_last_day_emp");
			if((month[0].value == "" || day[0].value == "" || year[0].value == "") && curRadio[8].checked) {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
			
			month = document.getElementsByName("last_day[month]");
			day = document.getElementsByName("last_day[day]");
			year = document.getElementsByName("last_day[year]");
			label = getLabelName("required_last_day");
			if((month[0].value == "" || day[0].value == "" || year[0].value == "") && curRadio[9].checked) {
				valid_form = false;
				bad_labels.push(label);
			} else {
				good_labels.push(label);
			}
		}
	}
	//end custom checking for online change form
	
	//color labels, do good ones first, because bad trumps good
	//this is for labels that correspond to multiple inputs, such as dates
	for (var i = 0; i < good_labels.length; i++) {
		good_labels[i].style.color = default_color;
	}
	for (var i = 0; i < bad_labels.length; i++) {
		bad_labels[i].style.color = highlight_color;
	}
	
	if(valid_form == false) {
		print_error( error_title, error_msg);
	}
	return valid_form;
}

function checkIfEmpty(field) {
	var result = true;
	label = getLabelName("required_"+field);
	element = document.getElementsByName(field);
	if(element[0].value == "") {
		label.style.color = highlight_color;
		result = false;
	} else {
		label.style.color = default_color;
	}
	return result;
}

function getLabelName(cname) {
	//grab the corresponding label
	temp_array = document.getElementsByTagName("label");
	var lname;
	var label_class_name;
	for( j = 0; j < temp_array.length; j++) {
		label_class_name = strip_nonrequired_class_names(temp_array[j].className);
		if (label_class_name == cname) {
			label_name = temp_array[j];
		}
	}
	return label_name;
}

function print_error(title, content) {
	var error_box = document.getElementById("error_box");

	//drop the title
//	document.getElementById("title_section").getElementsByTagName("h2")[0].style.display = "none";	

	error_box.innerHTML = "<h3>" + title + "</h3>" + content;
	error_box.style.display = "block";
}

function color_labels(class_name, color) {
	temp_array = document.getElementsByTagName("label");
	for( j = 0; j < temp_array.length; j++) {
		if (temp_array[j].className.indexOf(class_name) != -1) {
			temp_array[j].style.color = color;
		}
	}	
}

function has_index(array, index){
	var return_value = false;
	if(array[index]) {
		return_value = true;
	}
	if(array[index] == "") {
		return_value = true;
	}
	return return_value;
}

function combine_arrays(array1, array2){
	var newarray = new Array();
	for ( i = 0; i < array1.length; i++ ) {
		newarray.push(array1[i]);	
	}
	for ( i = 0; i < array2.length; i++ ) {
		newarray.push(array2[i]);	
	}
	return newarray;
}

function delConfirm(name){
	return confirm('Are you sure you would like to delete '+name);
}

function print_lines(lines, numlines) {
	var return_str = "";
	for( var i = 0; i < numlines; i++) {
		return_str += lines[i];	
	}
	return return_str;
}
function in_array(needle, haystack) {
	for (var i = 0; i < haystack.length; i++) {
		if (haystack[i] == needle) {
			return true;
		}
	}
	return false;
}

//this is to trim the other class names from input_array[i].className
//for example: <label class="name required_01 cooltext">...
//class_name becomes "required_01", not "name required_01 cooltext" 
function strip_nonrequired_class_names(class_string){
	class_string = "" + class_string;
	var ind = class_string.indexOf("required_");
	var class_name_length = class_string.indexOf(" ", ind);
	var class_name;
	if (class_name_length == -1)
	{
		class_name = class_string.substring(ind);
	} else {
		class_name = class_string.substring(ind, class_name_length);
	}
	return class_name;
}

