/**
 * universal js form checker
 *
 * (c) Timo Besenreuther
 *     EZdesign.de
 *
 * Created:       2008-09-09
 * Last modified: 2009-03-25
 */

function formchecker(pform, pformAction, pset) {
	var form            = pform;
	var formAction      = pformAction;
	var set             = pset;
	var mandatoryErrors = new Array();
	var agreeErrors     = new Array();
	var values          = new Array();
	
	// mandatory fields
	for (key in set.mandatory) {
		var element = document.getElementById(key);
		if (typeof(element.options) != 'undefined') {
			// selectbox
			if (element.selectedIndex) {
				var val = element.options[element.selectedIndex].getAttribute('name');
			} else {
				var val = element.options[0].getAttribute('name');
			}
		} else {
			// input
			var val = element.value;
		}
		if (val == '') {
			mandatoryErrors.push(set.mandatory[key]);
		}
	}
	
	// agreement checkbox
	for (key in set.agree) {
		var element = document.getElementById(key);
		if (!element.checked) {
			agreeErrors.push(set.agree[key]);
		}
	}
	
	// custom fields
	for (key in set.custom) {
		if (!set.custom[key].fn()) {
			agreeErrors.push(set.custom[key].error);
		}
	}
	
	// errors
	var errorHTML = new Array();
	if (mandatoryErrors.length > 0) {
		errorHTML.push('<b>'+set.text.mandatoryError+'</b><br />'+mandatoryErrors.join(', ')+'.');
	}
	if (agreeErrors.length > 0) {
		errorHTML.push('<b>'+agreeErrors.join('</b><br /><br /><b>')+'</b>');
	}
	
	var callback = function(addErrorHTML) {
		if (addErrorHTML.length > 0) {
			errorHTML.push(addErrorHTML);
		}
		if (errorHTML.length > 0) {
			// output error
			var err = document.getElementById(set.error);
			err.innerHTML = errorHTML.join('<br /><br />');
			err.style.display = 'block';
			// custom error handlers
			if (typeof(set.onError) != 'undefined') {
				for (var i = 0; i < set.onError.length; i++) {
					if (set.onError[i] == 'jumpToTop' && window.scroll) {
						// jump to top of page
						window.scroll(0,0);
					} else if (typeof(set.onError[i]) == 'function') {
						// custom function
						set.onError[i]();
					}
				}
			}
		} else {
			// submit form
			form.action = formAction;
			form.submit();
		}
	};
	
	// ajax
	if (typeof(set.postCheck) == 'function' && errorHTML.length == 0) {
		set.postCheck(callback);
	} else {
		callback('');
	}
}
