/// Mootools Form Check implementation   MOOCHECK
window.addEvent('domready', mooCheckInit);
function mooCheckInit(){
	$$('form.MooCheck').each(
		function(theForm){
			theForm.addEvent('submit',mooCheckSubmit);
			theForm.getElements('.MooCheck').each(
				function(theFormElement){
					theFormElement.addEvent('blur',mooFieldCheck);
				}
			);
		}
	);
}

function mooFieldCheck(){
	// Only return on errors..  after passing another error could occur..
	if(this.hasClass('MooNotEmpty') && this.getValue().trim()==''){
		mooRaiseError(this);
		return;
	} else if(this.hasClass('MooNotEmpty')){
		mooRemoveError(this);
	}
	if(this.hasClass('MooValidEmail') && /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,4}$/.test(this.getValue()) ){
		mooRemoveError(this);
	} else if(this.hasClass('MooValidEmail')){
		mooRaiseError(this);
		return;
	}
	if(this.hasClass('MooNotFirstOption') && this.selectedIndex==0){ // Selectbox may not have first option selected.
		mooRaiseError(this);
		return;
	} else if(this.hasClass('MooNotFirstOption')){
		mooRemoveError(this);
	}
}

function mooRaiseError(theElement){
	// Check if there is an _error field for this..
	if(theElement.hasClass('hasError')){
		return;
	}
	var theErrorInfo;
	if(theErrorInfo=$(theElement.getProperty('id')+'_error')){
		var ErrorElement = new Element('span',{'class':'error'});
		ErrorElement.appendText(theErrorInfo.getValue());
		ErrorElement.injectBefore(theErrorInfo);
		theElement.addClass('hasError');
	}
}

function mooRemoveError(theElement){
	var ErrorElement;
	if(theElement.hasClass('hasError')){
		ErrorElement=$(theElement.getProperty('id')+'_error').getPrevious();
		if(ErrorElement.getTag()=='span' && ErrorElement.hasClass('error')){
			ErrorElement.remove();
			theElement.removeClass('hasError');
		}
	}
}

function mooCheckSubmit(event){
	var event = new Event(event);
	this.getElements('.MooCheck').each(
		function(formElement){
			formElement.fireEvent('blur');
		}
	)
	if(this.getElements('.hasError').length>0){
		event.stop();
		
		/* VERSTEGEN SPECIAL EDITION !!
			Normally: 
			alert('Please correct all errors');
		*/
		var theFormAlert = new Custom.DefaultAlert(JS_FORM_ERROR, JS_PLEASE_CORRECT_FORM, 
				{alerthead: 'formfailurehead', alertbox: 'formfailurebox', alertbody: 'formfailurebody', autoclosetime:4000 }
				);
			
			theFormAlert.create();
		return;
	}
}