/* js validation for forms.

currently only supports checking that inputs and textareas are not empty.

usage:
1. assign the class "required" to the inputs you wish to check.
2. set onsubmit="checkRequiredFields" in the form.

on form submission, the required fields will be checked, and error messages
will be inserted in front of each one missing a value.

to be fully-featured, this could be extended to perform different checks
depending on the class of the input, e.g. requiredFloat.

this is for convenience. IT IS NOT A SUBSTITUTE FOR REAL VALIDATION, since
javascript is not secure against alteration by clients.
*/

var checkRequiredFields = function (form) {
	var valid = true;

	// remove any old error messages
	$ES('.errorlist', form).each(function (el) {
		el.dispose();
	})

	// create new error messages
	$ES('.required', form).each(function (el) {
		if ((el.type == 'text' && el.value == '') ||
			(el.type == 'textarea' && el.value == '')) {
			var errors = createErrorList(['This field is required.']);
			$(errors).injectBefore(el);
			valid = false;
		}
	});
	
	if (!valid) {
		// create notice next to submit button
		var notice = createErrorList(['Please correct the errors above.']);
		$(notice).injectBefore($E('.submit', form));
	}
	return valid;
}

var createErrorList = function (error_list) {
	var ul = document.createElement('ul');
	ul.setAttribute('class','errorlist');
	for (var i=0; i<error_list.length; i++) {
		var li = document.createElement('li');
		li.appendChild(document.createTextNode(error_list[i]));
		ul.appendChild(li);
	}
	return ul;
}

/* attribute selector hack

IE <= v6 doesn't support attribute selectors, e.g. input[type='checkbox'], so
we run a script to add classes to input fields equal to their type, in order to
target them with css.

based on http://www.dustindiaz.com/styling-inputs/
*/

window.addEvent('domready', function () {
	if ( !document.getElementsByTagName )
		return;
	var inputs = document.getElementsByTagName('input');
	var inputLen = inputs.length;
	for ( i=0;i<inputLen;i++ ) {
		if ( inputs[i].getAttribute('type') )
		inputs[i].className += ' '+inputs[i].getAttribute('type');
	}
	
});
