// on load add error boxes and validation checks to every form element

DFV = {};

// add an event to the current element
DFV.addEvent = function(el,evt,fxn) {
	// cross browser handling
	if(el.addEventListener) el.addEventListener(evt, fxn, false);
	else if(el.attachEvent) el.attachEvent("on" + evt, fxn);
}

// add error boxes and validation checks to every form element
DFV.setupForms = function() {
	// go through every form
	var forms = document.forms;
	for(var i = 0; i < forms.length; i++) {
		DFV.setupForm(forms[i]);
	}
}

DFV.setupForm = function(form)
{
		// go through every element of the current form
		var elements = form.elements;
		for(var ii = 0; ii < elements.length; ii++) {
			// add validation check
			DFV.addEvent(elements[ii],"blur", DFV.validate);
			// if an error box is specified use it
			if (elements[ii].getAttribute('dfv_error')) {
				elements[ii].dfv_error = document.getElementById(elements[ii].getAttribute('dfv_error'));
			}
			else { // otherwise create one
				elements[ii].dfv_error = document.createElement("div");
				elements[ii].dfv_error.className = "dfv_error";
				// add the error box immediately after the form element
				if(elements[ii].nextSibling)
					elements[ii].parentNode.insertBefore(elements[ii].dfv_error, elements[ii].nextSibling);
				else
					elements[ii].parentNode.appendChild(elements[ii].dfv_error);
			}
		}
}

// run through each validation function and collect all the errors
DFV.validate = function(ref) {
	// if a reference to the element can be established
	if (typeof ref == "object" && ref.tagName) {
		element = ref;
	}
	else
		element = DFV.getEventElement(ref);

	if (element) {
		// initially there are no errors
		var errorsExist=false;
		var warningsExist=false;
		var errors="";
		// get each class of the element
		var validation_array = element.className.split(/\s+/);
		// for each class of the element
		for (i = 0; i < validation_array.length; i++) {
			//if (!class || class == validation_array[i]) {
				// check to see if there is a corosponding function
				if (DFV["validate_"+validation_array[i]]) {
					// run the corrosponding function and append any errors if returned
					var curError = DFV["validate_"+validation_array[i]](element);
					if (curError[0]=="error") {
						errors += "<div class=\"dfv_error_box\">Oops! "+curError[1]+"</div>";
						errorsExist=true;
					}
					else if (curError[0]=="warning") {
						if (element.dfv_error.getAttribute('confirmed') != 'true') {
							errors += "<div class=\"dfv_warning_box\">Are you sure? "+curError[1]+"<input type=\"button\" class=\"right\" onclick=\"DFV.confirm(this)\" value=\"Confirm\"/><div class=\"clear\"></div></div>";
							warningsExist = true;
						}
					}
				}
			//}
		}
		
		// if errors display the current errors
		if (errorsExist || (warningsExist && element.dfv_error.getAttribute('confirmed') != 'true')) {
			DFV.displayErrors(element,errors);
		}
		// else clear any preexisting errors
		else {
			DFV.clearErrors(element);
		}

		if (warningsExist && element.dfv_error.getAttribute('confirmed') != 'true') {
			errorsExist = true;
		}
		if (errorsExist) {
			return false;
		}
		else {
			return true;
		}
	}
}

DFV.confirm = function(ref) {
	ref.parentNode.parentNode.setAttribute('confirmed', 'true');
	ref.parentNode.style.display='none';
}

// displays an error
DFV.displayErrors = function(ref,error) {
	ref.dfv_error.innerHTML = error;
	ref.dfv_error.style.display = "block";
}

// clears the error
DFV.clearErrors = function(ref) {
	ref.dfv_error.style.display = "none";
}

// validates all fields that need attention
// use on submit, returns true or false
// pass the form to be validated
DFV.validationChecker = function(ref) {
	var elements = ref.elements;
	var error = false;

	for(var i = 0; i < elements.length; i++) {
		if (elements[i].dfv_error) {
			if (!DFV.validate(elements[i])) {
				error = true;
			}
		}
	}

	if (error) {
		alert ("You did not fill out all the necessary information. Please correct the highlighted fields to continue.");
		return false;
	}
	else {
		return true;
	}
}
DFV.clearFormErrors = function(ref) {
	var elements = ref.elements;
	var error = false;

	for(var i = 0; i < elements.length; i++) {
		if (elements[i].dfv_error) {
			DFV.clearErrors(elements[i]);
		}
	}

	if (error) {
		alert ("You did not fill out all the necessary information. Please correct the highlighted fields to continue.");
		return false;
	}
	else {
		return true;
	}
}
// get an event handler's element
DFV.getEventElement = function(e) {
	if(!e) e = window.event;
	return e.currentTarget ? e.currentTarget : (e.srcElement ? e.srcElement : false);
}

// validates a phone number
DFV.validate_dfv_phone = function(ref) {
	var result = ["pass",""];

	var validation = /(^$)|(^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Phone numbers should be in the form 123-123-1234";
	}
	
	return result;
}

// validates a phone number
DFV.validate_dfv_phoneNumber = function(ref) {
	var result = ["pass",""];

	var validation = /(^$)|(^(1(-| )?)?\(?\d{3}\)?(-| )?\d{3}(-| )?\d{4}$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Phone numbers should be in the form 123-123-1234";
	}
	
	return result;
}

// validates a fax number
DFV.validate_dfv_fax = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Fax numbers should be in the form 123-123-1234";
	}
	return result;
}

// validates a phone number
DFV.validate_dfv_required = function(ref) {
	var result;
	var validation = /.+/;
	if (ref.value.search(validation) == -1) {
		//if match failed
		result = ["error", "Required"]
	}
	else {
		result = ["pass",""];
	}
	return result;
}

// validates a ssn
DFV.validate_dfv_ssn = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(\d{3}-\d{2}-\d{4})/;
	if (ref.value.search(validation)==-1) {//if match failed
		result[0] = "error";
		result[1] = "Social security numbers should be in the form 123-12-1234";
	}
	return result;
}

// validates an email address
DFV.validate_dfv_email = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^[^@]+@([^@.]+\.)+[^@.]{2,6}$)/;
	if (ref.value.search(validation)==-1) {//if match failed
		result[0] = "error";
		result[1] = "Invalid e-mail address";
	}
	return result;
}

// validates a Zip Code
DFV.validate_dfv_zip = function(ref) {
	var result = ["pass",""];
	var validation = /^(\s*|([a-zA-Z][0-9][a-zA-Z](\s|\-)*[0-9][a-zA-Z][0-9]|\d{5}(\-+\d*)*))$/;
	if (ref.value.search(validation)==-1) {//if match failed
		result[0] = "error";
		result[1] = "Zip Code must be in format \"12345\" or \"A0A 0A0\"";
	}
	return result;
}

// validates a credit card number
DFV.validate_dfv_cc_num = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^\d{15}\d?$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Credit card numbers must be at least 15 digits";
	}
	return result;
}

// validates a bank account number
DFV.validate_dfv_bank_account = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^\d{3}\d*$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Bank accounts must be at least three digits";
	}
	return result;
}

// validates a routing number
DFV.validate_dfv_routing_number = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^[0123]\d{8}$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Routing numbers must be nine digits and start with 0, 1, 2 or 3";
	}
	return result;
}

// validates a payment amount
DFV.validate_dfv_amount = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^\d+\.\d{2}$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Ammounts must be greater than 0 in the format 10.00";
	}
	return result;
}

// validates a payment amount
DFV.validate_dfv_month = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^01$)|(^02$)|(^03$)|(^04$)|(^05$)|(^06$)|(^07$)|(^08$)|(^09$)|(^10$)|(^11$)|(^12$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Month must be two digits";
	}
	return result;
}

// validates a payment amount
DFV.validate_dfv_year_2_digit = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^\d{2}$)/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "Years must be two digits";
	}
	return result;
}

DFV.validate_dfv_number = function(ref) {
	var result = ["pass", ""];
	var validation = /(^$)|(^\d+(\.\d+)?$)/;
	if(ref.value.search(validation) == -1) {
		result[0] = "error";
		result[1] = "Must be a number. Examples: 25, 50.17";
	}
	return result;
}

DFV.validate_dfv_percentage = function(ref) {
	var result = ["pass",""];
	var validation = /^\d+(\.\d+)?%?$/;
	if (ref.value.search(validation)==-1) { //if match failed
		result[0] = "error";
		result[1] = "A valid percentage should consist of only numbers and possibly a decimal point or percent sign. Examples: 7.25%, 5%";
	}
	return result;
}

// validates an email address
DFV.validate_dfv_url = function(ref) {
	var result = ["pass",""];
	var validation = /(^$)|(^https?:\/\/.+$)/;
	if (ref.value.search(validation)==-1) {//if match failed
		result[0] = "error";
		result[1] = "Invalid URL. URL's should start with http:// or https:// for example http://www.flowershopnetwork.com";
	}
	return result;
}

DFV.addEvent(window,"load", DFV.setupForms);
