/// 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.get('value').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.get('value')) ){
		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.get('value'));
		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 facebox = new Facebox({
 			title: JS_FORM_ERROR,
                        width: 350,
                        height: 100,
                        message: JS_PLEASE_CORRECT_FORM,
                        cancelValue: 'Ok',
                        cancelFunction: function(){
                            facebox.close();
                        }
 		});
 		facebox.show();

	
		return;
	}
}