/**
 * @author Dave Shepard
 * Form validation script. Add the class "formValidate" to any <form> tag and
 * the class "required" to any INPUT, SELECT, or TEXTAREA that is required. The
 * Form tag must have an ID value defined and the individual elements within the
 * form must have IDs defined as well. The IDs of the elements is not important,
 * but it is necessary for like comparison.
 *
 * Validates against empty fields, email field formatting, and required checkboxes
 * (for terms and conditions and the like). Submit buttons will be disabled
 * until all fields are valid.
 *
 * Implementation:
 * <form action="formprocessor.php" method="post" class="formValidate" id="form_id">
 * <input type="text" class="required" />
 *
 * Submit buttons will be disabled and have the "disabled" class assigned to them
 * when they are disabled. <input type="image" /> buttons will use a naming syntax
 * for the "src" attribute to display a "disabled" image.
 *
 * <input type="image" /> Image "src" syntax:
 *     "imagename_i.gif" - Enabled (idle) image
 *     "imagename_d.gif" - Disabled image
 *
 * For the image "src" syntax, the file name must stay the same except for the _i and
 * _d notations at the end of the file name. You may change file types (GIF/JPG/PNG)
 * between states if so desired.
 * 
 * UPDATE [June 11, 2008]:
 * New! Added support for multiple submit buttons! Multiple submit buttons (type="submit"
 * or type="image") are now supported. Also modified attachment to be on DOM ready. An
 * extension of the Prototype library to enable the onDOMReady method has been included
 * as part of the script. This will not conflict with existing onDOMReady extensions.
 */

// Try extending the Prototype library with an onDOMReady method
try {
    Object.extend(Event, {
        _domReady : function() {
            if (arguments.callee.done) return;
            arguments.callee.done = true;
            if (this._timer) clearInterval(this._timer);
            this._readyCallbacks.each(function(f) { f() });
            this._readyCallbacks = null;
        },
        onDOMReady : function(f) {
            if (!this._readyCallbacks) {
                var domReady = this._domReady.bind(this);
                if (document.addEventListener) document.addEventListener("DOMContentLoaded", domReady, false);
                if (/WebKit/i.test(navigator.userAgent)) {
                    this._timer = setInterval(function() {
                        if (/loaded|complete/.test(document.readyState)) domReady();
                    }, 10);
                }
                Event.observe(window, 'load', domReady);
                Event._readyCallbacks =  [];
            }
            Event._readyCallbacks.push(f);
        }
    });
} catch(e) {
}

Event.onDOMReady(function(){
	// Grab all forms to be validated
	$$('form.formValidate').each(function(theForm,ind) {
		// Set checkboxes to blur automatically on click - required for Internet
		// Explorer compatability
		$$('#'+theForm.identify()+' input[type="checkbox"]').each(function(checks){
			checks.observe('focus', function(){
				this.blur();
			});
		});

		// Get all the required elements in the form
		var requiredElems = $$('#'+theForm.identify()+' input.required','#'+theForm.identify()+' textarea.required','#'+theForm.identify()+' select.required');

		// Parse through each required element in the form and assign the in-line
		// form validation check on each field.
		requiredElems.each(function(rE){
			// Make the exception for Internet Explorer based browsers to do the checkbox
			// check on change instead of blur.
			if (rE.type == "checkbox" && Prototype.Browser['IE'] == false) {
				rE.observe('change', function(){
					validateForm(theForm.identify(), requiredElems, rE.identify());
				});
			} else {
				rE.observe('blur', function(){
					validateForm(theForm.identify(), requiredElems, rE.identify());
				});
			}
			// Add a special case to also validate TEXTAREA fields while the user
			// is typing in the field. This is to enable the submit button without
			// requiring a blur() action to happen when a user is typing a comment
			if(rE.match("textarea")) {
				rE.observe('keydown',function(){
					validateForm(theForm.identify(), requiredElems, rE.identify());
				});
			}
		})

		// Identify the submit button ID for use in the initial validation
		var submitBtn = new Array();
		theForm.select('input[type="submit"]','input[type="image"]').each(function(s){
			submitBtn.push(s.identify());
		});

		// Probably not necessary, but this will prevent the form from being submitted
		// without validating first. This will interupt the submit of the form to run the
		// validation script first.
		theForm.writeAttribute("onsubmit","return validateForm('"+theForm.identify()+"',"+requiredElems+",'"+submitBtn+"');");

		// Run initial form validation on page load. This will disable the submit button,
		// but will not display any error messages in-line on the fields
		validateForm(theForm.identify(),requiredElems,theForm.identify());

	});



	// BEGIN :: CUSTOM FORM SPECIFIC CODE FOR CHAMPION SOUND SIGNUP FORM
	// =========================================================================
	// Country validation. If the country is not set to the United States,
	// remove the City and State fields from the DOM. If the user switches
	// back to the United States, place the fields back in the DOM
	if($('id_country')){
		$('id_country').observe('change', function(){
			if(this.value != "USA") {
				if($('li_city')){
				$('li_city').remove();
				}
				if($('li_state')){
					$('li_state').remove();
				}
			} else {
				if(!$('li_city')) {
					cityStateDropDowns = '<li id="li_city"><label id="label_city" for="id_city"><span class="required">* </span>City</label><input tabindex="5" type="text" name="account[city]" id="id_city" class="textfield required" /></li><li id="li_state"><label id="label_state" for="id_state"><span class="required">* </span>State</label><select tabindex="6" name="account[state]" id="id_state" class="required"><option value="">Other / NA</option><option value="Alabama">Alabama</option><option value="Alaska">Alaska</option><option value="Arizona">Arizona</option><option value="Arkansas">Arkansas</option><option value="California">California</option><option value="Colorado">Colorado</option><option value="Connecticut">Connecticut</option><option value="Delaware">Delaware</option><option value="Florida">Florida</option><option value="Georgia">Georgia</option><option value="Hawaii">Hawaii</option><option value="Idaho">Idaho</option><option value="Illinois">Illinois</option><option value="Indiana">Indiana</option><option value="Iowa">Iowa</option><option value="Kansas">Kansas</option><option value="Kentucky">Kentucky</option><option value="Louisiana">Louisiana</option><option value="Maine">Maine</option><option value="Maryland">Maryland</option><option value="Massachusetts">Massachusetts</option><option value="Michigan">Michigan</option><option value="Minnesota">Minnesota</option><option value="Mississippi">Mississippi</option><option value="Missouri">Missouri</option><option value="Montana">Montana</option><option value="Nebraska">Nebraska</option><option value="Nevada">Nevada</option><option value="New Hampshire">New Hampshire</option><option value="New Jersey">New Jersey</option><option value="New Mexico">New Mexico</option><option value="New York">New York</option><option value="North Carolina">North Carolina</option><option value="North Dakota">North Dakota</option><option value="Ohio">Ohio</option><option value="Oklahoma">Oklahoma</option><option value="Oregon">Oregon</option><option value="Pennsylvania">Pennsylvania</option><option value="Rhode Island">Rhode Island</option><option value="South Carolina">South Carolina</option><option value="South Dakota">South Dakota</option><option value="Tennessee">Tennessee</option><option value="Texas">Texas</option><option value="Utah">Utah</option><option value="Vermont">Vermont</option><option value="Virginia">Virginia</option><option value="Washington">Washington</option><option value="West Virginia">West Virginia</option><option value="Wisconsin">Wisconsin</option><option value="Wyoming">Wyoming</option></select></li>';
					new Insertion.After('li_country', cityStateDropDowns);
					var thisFormID = $('id_city').up('form').identify();
					var requiredElems = $$('#'+thisFormID+' input.required','#'+thisFormID+' textarea.required','#'+thisFormID+' select.required');
					$('id_city','id_state').each(function(rE){
						rE.observe('blur', function(){
							validateForm(thisFormID, requiredElems, $(this).identify());
						});
					});
					validateForm(thisFormID,requiredElems,thisFormID);
				}
			}
		});
	}
	// =========================================================================
	// END :: CUSTOM FORM SPECIFIC CODE FOR CHAMPION SOUND SIGNUP FORM

});


function validateForm(formID,requiredElems,thisElem) {
	// Identify the submit button element's ID
	var submitBtn = new Array();
	$(formID).select('input[type="submit"]','input[type="image"]').each(function(s){
		submitBtn.push(s.identify());
	});

	// Check if this is the initial run (thisElem is the same as formID)
	if($(thisElem) == $(formID)) {
		isInitial = true;
	} else {
		isInitial = false;
	}

	// Check if this is the onsubmit action (thisElem is the submit button/image)
	if(submitBtn.indexOf($(thisElem).identify()) != -1) {
		isSubmit = true;
	} else {
		isSubmit = false;
	}

	// Validate the required fields
	requiredElems.each(function(rE){
		// Check if this is the current field
		if($(thisElem) == rE) {
			sameElem = true;
		} else {
			sameElem = false;
		}

		// Define default values for validation
		valid = true;
		isEmail = false;

		// Check if this is a checkbox and validate based off of checked boolean
		if (rE.nodeName == "INPUT" && rE.type == "checkbox") {
			if (rE.checked) {
				valid = true;
			}
			else {
				valid = false;
			}
		}
		else {
			// Check if the input field is empty
			if (rE.value.blank() == true) {
				valid = false;
			}
			else {
				// Check if the input field is an email address and validate against proper formatting
				if ((rE.identify().toLowerCase().indexOf("email") != -1 ||
				rE.readAttribute("name").toLowerCase().indexOf("email") != -1 ||
				rE.readAttribute("class").toLowerCase().indexOf("email") != -1) &&
				rE.match("input")) {
					isEmail = true;
					if (!/^\w+([\+\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(rE.value)) {
						valid = false;
					}
				}
			}
		}

		// Check to see if the error message should be shown
		if(isInitial == true) {
			// This is the initial run, do not show in-line error messages
			showErr = false;
		} else {
			if(isSubmit == true) {
				// This is the submit check of the form, show all in-line error messages
				showErr = true;
			} else {
				if(sameElem == true) {
					// This is the element the user just came from, show in-line error messages
					showErr = true;
				} else {
					// This is not the element the user just came from, do not show in-line error messages
					showErr = false;
				}
			}
		}

		// Check if the field failed validation
		if(valid == false) {
			// Add a class to the invalid field to check for full form validation
			rE.addClassName("invalidFormField");
			// Show errors if allowed to
			if(showErr == true) {
				// If this form is formatted in a list, assign the error class to the input's parent <li>
				if (rE.up('li')) {
					rE.up('li').addClassName('error');
				}
				// Create the error message if it does not exist already
				if(document.getElementById(rE.identify()+"_error") == null) {
					var errorMsg = document.createElement("SPAN");
						errorMsg.id = rE.identify()+"_error";
						errorMsg.className = "error";
						rE.parentNode.appendChild(errorMsg);
				}
				// If this is an email address, ask user to format email properly
				if (isEmail == true) {
					$(rE.identify() + "_error").update("Please make sure you enter a valid email (<em>user@domain.com</em>)");
				} else {
					// Check the form field type and provide errors appropriate to the field type
					if (rE.nodeName == "INPUT" || rE.nodeName == "TEXTAREA") {
						if (rE.readAttribute("type") == "checkbox") {
							// Checkbox error message
							$(rE.identify() + "_error").update("Please make sure you have agreed to the above terms");
						}
						else {
							// Text field error message
							$(rE.identify() + "_error").update("Please make sure you enter something for this field");
						}
					}
					if(rE.nodeName == "SELECT") {
						// Drop-down error message
						$(rE.identify() + "_error").update("Please make a choice for this field");
					}
				}
			}
		} else {
			// This field has passed validation, remove all error classes and error messages
			rE.removeClassName("invalidFormField");
			if (rE.up('li')) {
				rE.up('li').removeClassName('error');
			}
			if (document.getElementById(rE.identify() + "_error")) {
				$(rE.identify() + "_error").remove();
			}
		}
	}); // End requiredElems.each

	// Count the elements with the invalidFormField class in this form and validate against
	// the entire form to disable or enable the submit button.
	if($$('#'+formID+' .invalidFormField').length > 0) {
		submitBtn.each(function(s){
			$(s).disabled = true;
			$(s).addClassName('disabled');
			if ($(s).type == "image") {
				oldSrc = $(s).src;
				if (oldSrc.indexOf("_i.") != -1) {
					$(s).writeAttribute('src', oldSrc.replace("_i.", "_d."));
				}
			}
		});
		return false;
	} else {
		submitBtn.each(function(s){
			$(s).disabled = false;
			$(s).removeClassName('disabled');
			if ($(s).type == "image") {
				oldSrc = $(s).src;
				$(s).writeAttribute('src', oldSrc.replace("_d.", "_i."));
			}
		});
		return true;
	}
}



