var InputValidator = new Class({ 
	
	Implements: Log,
	
	options: {
		mandatory_class: 'mandatory',
		error_class: 'error'
	},
	
	initialize: function( form ){
		if( !form || form.tagName != 'FORM'  ){
			return;
		}
		this.enableLog().log('Initializing InputValidator');
		this.form = $(form);
		this.setMandatoryElements();
	},
	
	setMandatoryElements: function(){
		this.elements = this.form.getElements('input.'+this.options.mandatory_class);
		this.elements.each( this.setDefaults, this );
		this.form.addEvent( 'submit', this.checkDefaults.bind(this) );
	},
	
	setDefaults: function(item, index, array){
		if( ! this.isEmpty(item) ){
			item.removeClass(  this.options.mandatory_class );
		}else if( item.getProperty('alt') != '' ){
			item.value = item.alt;
		}
		
		item.addEvent( 'focus', this.gotFocus.bind(this) );
		item.addEvent( 'blur', this.checkInput.bind(this) );
	},
	
	gotFocus: function( e ){
		if( !e ) var e = window.event;
		
		var item = $(e.target||e.srcElement);
		
		if( item.alt != '' ){
			if( item.value == item.alt ){
				item.value="";
				item.removeClass( this.options.mandatory_class );
			}
		}
	},
	
	checkInput: function ( e  ){
		if( !e ) var e = window.event;
		
		var item = $(e.target||e.srcElement);
		
		if( this.isEmpty( item ) ){
			this.setInputError( item, true );
			return false;
		}
		item.removeClass( this.options.error_class );
		return true;
	},

	isEmpty: function( item ){
		if( item.tagName != "INPUT" ){
			Error("kein Input-Element");
		}
		if( item.getAttribute("type") == "text" ){
			var text=item.value;
			return text.length == 0 || text == item.alt;
		}
	},

	setInputError: function(item, hasDefault ){
		if( hasDefault ){
			item.value = item.alt;
			$(item).addClass(this.options.mandatory_class);
		}
	},
	
	checkDefaults: function(e){
		var ok = this.elements.every( this.checkDefault, this );
		return ok;
	},
	
	checkDefault: function(item, index, array){
		if( item.hasClass(this.options.mandatory_class)){
			if( item.value == '' || item.value == item.alt ){
				item.focus();
				item.addClass( this.options.error_class );
				return false;
			}
		}
		return true;
	}
	

});
