var theForm;
var theFormID;
var required;

// Define error messages and split the required fields
var errExists;
var errorID		= 'errormsg';
var errorClass	= 'error'
var errorMsg	= 'Please fix the required fields indicated ';
var errorSrc	= '/jscripts/images/alert.gif';
var errorAlt	= 'Error';
var errorTitle	= 'This field has an error!';

// create image, add to and colourise the error fields
var errorIndicator = '<img alt="'+errorAlt+'" src="'+errorSrc+'" title="'+errorTitle+'" class="errorIndicator"/>';

function checkSubmitForm(theForm){
// Test if DOM is available and there is an element called required
	if(!document.getElementById || !document.createTextNode){return;}

	theFormID	= $(theForm).attr("id");
	required	= $("#"+theFormID+" [id^='required']").val();
	errExists	= false;
	
	if(required!=""){
		// Cleanup old mess
		// if there is an old errormessage field, delete it
		$("#"+errorID).remove();
		$(".errorIndicator").remove();
		$("."+errorClass).removeClass(errorClass);

		// loop over required fields
		var reqfields = required.split(',');
		for(var i=0;i<reqfields.length;i++){
			// check if required field is there
			var f = eval("theForm."+reqfields[i]);
			if(!f){continue;}
			// test if the required field has an error,
			// according to its type
			if(typeof f.type != "undefined"){
				switch(f.type.toLowerCase())
				{
					case 'text':
					case 'password':
						if(f.value=='' && f.id.toLowerCase().indexOf("email")==-1){cf_adderr(f)}
						// email is a special field and needs checking
						if(f.id.toLowerCase().indexOf("email")!=-1 && !cf_isEmailAddr(f.value)){cf_adderr(f)}
					break;
					case 'textarea':
						if(f.value==''){cf_adderr(f)}
					break;
					case 'checkbox':
						if(!f.checked){cf_adderr(f)}
					break;
					case 'select-one':
						if(!f.selectedIndex && f.selectedIndex==0){cf_adderr(f)}
					break;
				}
			}else{
				// radio does not return type (i think even checkbox does the same) - so let's use jQuery for them
				var theField = $("input[@name="+reqfields[i]+"]");
				var theFieldVal = $("input[@name="+reqfields[i]+"][@checked]").val();
				if(typeof theFieldVal == "undefined" || theFieldVal == ""){
					$(theField[0]).before(errorIndicator);
					errExists = true;
				}
			}
		}
	}
	if(errExists){
		$("#"+theFormID)
			.after('<div id="'+errorID+'"><p>'+errorMsg+' '+errorIndicator+'</p></div>');
		return false;
	}
	return true;
}
function cf_adderr(o){
	$(o)
		.addClass(errorClass)
		.before(errorIndicator);
	errExists = true;
}
function cf_isEmailAddr(str){
	return str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
}

