AdditionalValidationRequired = false;
var Validator =
{
	readyexps :
	{
		"email" : "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*",
		"Email field." : "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*",
		"required" : ".+",
		"Required field." : ".+",
		"digits" : "[0-9+]",
		"egn" : "[0-9]{10}",
		"username" : "[0-9a-zA-z]{2,100}",
		"password" : "[0-9a-zA-z]{4,100}",
		"length2" : "{2,100}",
		"bulstat" : "^[0-9]{9,13}$",
		"postcode" : "[0-9]{4}"
	},

	onLoad : function ()
	{
		var forms = document.getElementsByTagName ("form");
		for(var i = 0; i< forms.length; i++)
			if (forms[i].className == "validate")
			{
                
				forms[i].onsubmit = this.Validate;
				this.setupFields(forms[i]);
			}
	},

	setupFields : function (form)
	{
			var labels = form.getElementsByTagName ("label");
			for (var i = 0; i < labels.length; i++)
			{
                    
					var lbl = labels[i];
					if (lbl.title == "") continue;
                    this.InputPrepare(lbl);
            }
	},
	
    setInvalid : function ()
    {
        this.errSpan = document.createElement('span');
        this.errSpan.innerHTML = this.errorMsg;
        this.parentNode.className = "err";
        this.parentNode.appendChild(this.errSpan);
    },
    
    setValid : function  ()
    {
        this.parentNode.className = "";	
        if (this.errSpan != null)
            this.parentNode.removeChild(this.errSpan);
        this.errSpan = null;
    },
    
    InputPrepare : function (label)
    {
          
            var inp = document.getElementById(label.htmlFor);
            
            // transfer the methods
            inp.setInvalid = this.setInvalid;
            inp.setValid = this.setValid;
            inp.Check = this.Check;
            inp.onchange = this.OnInputChange;
            
            
            inp.req = new RegExp (Validator.readyexps[label.title] != null) 
			? Validator.readyexps[label.title] 
			: label.title;
            label.firstChild.nodeValue += ' *';
            inp.errorMsg = inp.title == null ? " *" : inp.title;
     
    },
    
    OnInputChange : function ()
    {
        this.Check();
    },
    
	Check : function ()
	{
        this.setValid();

        if (!this.value.match (this.req))
        {   // we do not match
            this.setInvalid();
            return false;
        }
        
        return true;
	},
	
	
	Validate : function ()
	{
        var validForm = true;
        
        for (var i = 0; i < this.elements.length; i ++)
        {
            
            var el = this.elements[i];
            if (typeof(el.Check) == 'undefined') continue;
            if (!el.Check())
                validForm = false;
        }
        
        if(validForm && AdditionalValidationRequired)
        {
        	return eval(AdditionalValidationRequired+"();");	
        }
        
        return validForm;
	}
}

window.addListener (Validator);
