// JavaScript Document

var FormChecker = Class.create();

FormChecker.prototype = {
  
    initialize:function(_itemarray)
    {
		this.err = new Array();
		this._array = _itemarray;
		this.errormsg = $("errormsg");
		this.amount = this._array.length;
		this.isOK= true;
		this.refferer = $("refferer").value = document.location.href;
		
		this.checkFields(this._array);

    },
	
	checkFields:function(_array)
	{
		for (i=0; i< this.amount; i++)
		{
			
			//Check, if fields are set
			if($(_array[i][0]).value == "")
			{
				this.addError(_array[i][0]);
				this.isOK = false;
			}
			
			 switch (_array[i][1])
			 {
				 case ("string"):
				 		//alert("STRING: "  +  _array[i][0]);
						break;
				 case ("email"):
					 	var z = this.validEmail($(_array[i][0]).value);
						if(z != false) 
						{ 
							$(_array[i][0]).value = z; 
						} else { 
							this.addError(_array[i][0]);
							this.isOK = false; 
						}						
						break;
				 case ("phone"):
				 		var z = this.validPhone($(_array[i][0]).value);
						if(z != false) 
						{ 
							$(_array[i][0]).value = z; 
						} else { 
							this.addError(_array[i][0]);
							this.isOK = false; 
						}
						break;						
			 }
		}
		
		//this.reportError();
		this.setErrorFields();
		
		return this.isOK;
	},

	validEmail:function(str)
	{
		//var b =str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
		//var b = str.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
		var b=str;
		if((b != null)) { return b; }
		
		return false;
	},

	validPhone:function(str)
	{
		var b = str.replace(/[^0-9]/g, '');
		//(b.length >= 9 && b.length <= 16)
		if((b != null)) { return b; }
		return false;
	},
    
    itemIn:function(_item)
    {
		for (w=0; w<=this.err.length; w++)
		{
			if(this.err[w] == _item) { return true; }
		}
    },
    
    addError:function(_errorfield)
    {
		if(this.itemIn(_errorfield)) { return; }
		this.err.push(_errorfield);
    },
	
	reportError:function()
    {
		alert("THIS ERRORS ARE REPORTED: " + this.err);
    },
    
    setErrorFields:function()
    {
		this.resetFields();
		
		if(this.err.length == null || this.err.length == 0)  
		{ 
			this.isOK = true; 
			return; 
		}

		for (a=0; a<this.err.length; a++)
		{
			$(this.err[a]).className = "error";
		}
		
		this.setNotice();
    },
	
	resetFields:function()
    {
		for (b=0; b<this.amount; b++)
		{
			$(this._array[b][0]).className = "";
		}
		this.errormsg.className = ""; 
		this.errormsg.innerHTML = "";		
    },
	
	setNotice:function()
	{
		if (this.err.length == null)  { 
			this.errormsg.className = ""; 
			this.errormsg.innerHTML = "";
			return; 
		}
		
		this.errormsg.className = "errormsg";
		this.errormsg.innerHTML = "Wir haben " + this.err.length + " Fehler gefunden.<br /> Bitte f&uuml;lle alle Pflichtfelder aus und korrigiere falsche Angaben.";
	}
	
} 
