//// Form validation
// 16/02/05 JM: Created
// 04/06/05 JM: Added MsgErr functions (at SB v. 0.4)
// 24/08/05 JM: Added SubmitBtn locking (at SB v. 0.6)

function sbForm(sForm)	// optionally: MsgErrStart(v0.4+), MsgErrEnd(v0.4+), SubmitBtn (v0.6+)
{
	/// Properties
	this.Form=sForm;
	this.Fields=new Array();
	this.FieldCount=0;
	this.MsgErrorStart=(arguments.length>1?arguments[1]:"The following errors were found in the form:") + "\n";
	this.MsgErrorEnd=(arguments.length>2?arguments[2]:"");
	this.SubmitBtn=(arguments.length>3?arguments[3]:"");

	/// Methods
	this.Add=sbFormAdd;
	this.Check=sbFormCheck;


	/// Function definitions
	// Add a form checker item
	function sbFormAdd(oEl)
	{
		this.Fields[this.FieldCount]=oEl;
		this.FieldCount++;
	} // sbFormAdd


	// Do the form check
	// Returns: Was the
	function sbFormCheck()
	{
		var oForm=document.forms[this.Form];
		var sError="";
		var sValue, bOK, lLen, oField;

		for (var intLoop=0;intLoop<this.FieldCount;intLoop++)
		{
			oField=this.Fields[intLoop];

			// Clean
			sValue=oForm[oField.Field].value;
			if (sValue==null) sValue="";
			sValue=sValue.replace(/^(\s)*/,"").replace(/(\s)*$/,"");	// Trim (start then end)

			// Save it back
			oForm[oField.Field].value=sValue;

			// Do checks
			lLen=sValue.length;

			bOK=!(oField.Required && lLen==0);										// Required?
			if (bOK) bOK=((lLen==0) || !(oField.MinLen>0 && lLen<oField.MinLen));	// Min
			if (bOK && oField.MaxLen>=oField.MinLen && 0<oField.MaxLen) bOK=lLen<=oField.MaxLen;	// Max

			if (!bOK && oField.ErrorMessage.length>0) sError+=oField.ErrorMessage+"\n";
		}


		// Show an error
		if (sError!="") alert(this.MsgErrorStart + sError + this.MsgErrorEnd);


		return (sError=="");
	} // sbFormCheck
}

//// A form field
function sbFormFld(sField, bReq, lMinLen, lMaxLen, sMsgError)
{
	/// Properties
	this.Field=sField;
	this.Required=bReq;
	this.MinLen=lMinLen;
	this.MaxLen=lMaxLen;
	this.ErrorMessage=sMsgError;
}
