
/*									*/
/*	Netfinity Form Validator v1.1 	*/
/*	(c)2007 Netfinity, INC.			*/
/*									*/
/*	last updated 09/10/07			*/


function NFY(f){
	//alert('Constructor');
	var ob 	= this;
	this.fm	= document.forms[f];
	
	if(!document.forms[f]) {
		alert('No such form: ' + f);
		return false;
	}
	
	this.fm.onsubmit = function() {
		return ob.validateForm();
	};
}


/* member variables */
NFY.prototype.fm = null;
NFY.prototype.fo = [];
NFY.prototype.fc = -1;
NFY.prototype.eh = null;

/* methods */
NFY.prototype.validateForm = function () {
	for(var i=0; i<this.fo.length; i++) {
		
		var el = this.fm[this.fo[i].field];

		/* "borrowed" from gen_validator */
		var epos = this.fo[i].req.search("=");
		if(epos >= 0) {
			var cmd = this.fo[i].req.substring(0,epos); 
			var cmv	= this.fo[i].req.substr(epos+1); 
		}
		else {
			cmd = this.fo[i].req;
		}
		
		switch(cmd) {
			case "req" :
				if(el.value.length<1) {
					alert(this.fo[i].desc);
					el.focus();
					return false;
				}
				break;
			case "numbers" :
				var pos = el.value.search("[^0-9]");
				if(pos>=0 || el.value.length<1) {
					alert(this.fo[i].desc + ' : numbers only.');
					el.focus();
					return false;
				}
				break;
			case "email" :
				if(!this.isEmail(el.value)) {
					alert(this.fo[i].desc);
					el.focus();
					return false;					
				}			
			break;
			case "dontselect" :
				if(el.selectedIndex==cmv) {
					alert(this.fo[i].desc);
					el.focus();
					return false;	
				}
			break;
			case "radio" :
				var ch = false;
				for(j=0; j<el.length; j++) {
					if(el[j].checked) { ch=true; }
				}
				
				if(!ch) {
					alert(this.fo[i].desc);
					return false;
				}
			break;			
			case "checkone" :
				var ok = false;
				var cb = document.getElementsByName(this.fo[i].field);
				for(var j=0; j<cb.length; j++) {
					if (cb[j].checked) {
						ok = true;
					}
				}
				if(!ok) {
					alert(this.fo[i].desc);
					return false;
				}
			break;
			/* check duplicates (temp) */
			default:
				var ell = this.fm[this.fo[i].req];
				if(el.value!=ell.value) {
					alert(this.fo[i].desc);
					el.focus();
					return false;
				}
			break;
		}
	}

	//alert('form passed');
	if(this.eh) {
		//alert("Extra Handler");
		return eval(this.eh + '();');
		return false;
	}
	return true;
};

NFY.prototype.addField = function(field, req, desc) {
		var x = ++this.fc;

		if(!this.fm[field]) {
			alert('No such form field \"' + field + '\" in form');
			return false;
		}
		
		this.fo[x]			= {};
		this.fo[x].field	= field;
		this.fo[x].req		= req;
		this.fo[x].desc		= desc;
		
};

NFY.prototype.addHandler = function(hnd) {
	this.eh = hnd;
};

NFY.prototype.isEmail = function(str) {
	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
};