//==============================================================================
// valdation functions, Ilya Bulah

ValidatorHelper = {
	'regexp_non_digit': /[^\d]+/g,
	'regexp_phone': /[^\d\(\)\-\+\ ]+/g,
	'regexp_non_phone': /\d\d\d\-?\d\d\-?\d\d+/g,
	'regexp_non_url': /(www\.|http:)[^\s]{3,}/g,
	'regexp_non_email': /\S{2,7}@\S{3,7}/g
};


function addValidator(obj, fn){
	addEvent(obj, 'change', fn);
	addEvent(obj, 'input', fn);
	addEvent(obj, 'blur', fn);
	addEvent(obj, 'keyup', fn);
}

//==============================================================================
//validators
function numberValidator(){
	if (!(ValidatorHelper.regexp_non_digit.test(this.value))) return;
	this.value = this.value.replace(ValidatorHelper.regexp_non_digit, '');
}


function phoneValidator(){
	if (!(ValidatorHelper.regexp_phone.test(this.value))) return;
	this.value = this.value.replace(ValidatorHelper.regexp_phone, '');

}

function maxonTextValidator(){
	if (!(ValidatorHelper.regexp_non_phone.test(this.value))
	&& (!ValidatorHelper.regexp_non_url.test(this.value))
	&& (!ValidatorHelper.regexp_non_email.test(this.value))
	) return;
	this.value = this.value.replace(ValidatorHelper.regexp_non_phone, '');
	this.value = this.value.replace(ValidatorHelper.regexp_non_url, '');
	this.value = this.value.replace(ValidatorHelper.regexp_non_email, '');
}

function sizeValidator(){
	//alert(this.value.length < this.maxsize);
	if (this.value.length > this.maxsize){
		this.value = this.value.substring(0, this.maxsize);
	}
	//if (this.value.length > this.maxsize) return false;
}

//==============================================================================
function setupValidators(f, validators){
	for (validator in validators){
		switch(validator){
			case 'not_www': fn = maxonTextValidator; break;
			case 'digits': fn = numberValidator; break;
			case 'phone': fn = phoneValidator; break;
			default: continue;
		}

		type = validators[validator];
		for (field in type){
			if (!f[type[field]]) continue;

			//alert(type[field]);

			obj = f[type[field]];

			//alert(typeof obj)

			//tupnyak!
			/*
			if ((typeof obj) != 'object'){
				for (el in obj){
					if (obj[el].type == 'hidden' || obj[el].type == 'undefined') continue;
					obj = obj[el];
					break;
				}
			}
			*/
			//alert(obj.name);
			addValidator(obj, fn);
		}
	}
}

