window.Validators = [];

function ValidTextBox(oTbx){
	this.textBox = oTbx;
	this.IsValid = true;
	this.initValidator();
	this.init();
}
//Setup Events and add this guy to the list of validators in this page
ValidTextBox.prototype.init=function(){
	var oThis = this;
	window.Validators[window.Validators.length] = oThis;
	//Setup Blur handler
	this.textBox.onblur = function (){
        oThis.handleBlur();
	}; 
};

//Try and grab all of the custom attributes to see what we need to validate
ValidTextBox.prototype.initValidator=function(){
	this.ReValidationMsg = getElementAttribute(this.textBox.id,'re_msg');
	if(getElementAttribute(this.textBox.id,'re_match'))
		this.REMatch = new RegExp(getElementAttribute(this.textBox.id,'re_match'));
	else
		this.REMatch = null;
		
	this.EmptyValidationMsg = getElementAttribute(this.textBox.id,'empty_msg');
	
	this.ErrorElement = Get(getElementAttribute(this.textBox.id,'err_element'));
	if(getElementAttribute(this.textBox.id,'err_label'))
		this.ErrorLabel = Get(getElementAttribute(this.textBox.id,'err_label'));
};

//onBlur Handler
ValidTextBox.prototype.handleBlur = function(){
	var isOk = true;
	if(this.EmptyValidationMsg){
		isOk = (this.textBox.value.trim().length > 0);
		if(!isOk){
			this.ShowEmptyError();
			this.IsValid = isOk;
			return;
		}
	}
	
	if(this.REMatch && this.ReValidationMsg){
		isOk = this.validateRegexp();
		if(!isOk){
			this.ShowReError();
			this.IsValid = isOk;
			return;
		}
	}	
	this.IsValid = true;
	this.HideError();
};
//Check the RegEx
ValidTextBox.prototype.validateRegexp = function(){
	return (this.REMatch.test(this.textBox.value) && this.REMatch.exec(this.textBox.value)[0] == this.textBox.value)
}

ValidTextBox.prototype.ShowEmptyError = function(){
	if(this.ErrorElement){
		this.ErrorElement.innerHTML = this.EmptyValidationMsg;
		Show(this.ErrorElement.id);
	}
	if(this.ErrorLabel)
		this.ErrorLabel.style.color = 'red';
}

ValidTextBox.prototype.ShowReError = function(){
	if(this.ErrorElement){
		this.ErrorElement.innerHTML = this.ReValidationMsg;
		Show(this.ErrorElement.id);
	}
	if(this.ErrorLabel)
		this.ErrorLabel.style.color = 'red';
};

ValidTextBox.prototype.HideError = function(){
	if(this.ErrorElement)
		Hide(this.ErrorElement.id);
	if(this.ErrorLabel)
		this.ErrorLabel.style.color = '';
};

