//<script language="javascript">
/*=============================================================================
 WebSolvers Framework Library
 Copyright 2003, WebSolvers, Inc., All Rights Reserved.

 Library Validation
 Cross-Browser/Platform common Validation library
 
 Revision History:
 6-4-03 Created

 Provides
 The following validation types are provided
	skip
	req([if variable][, [if value]])
	join([string])
	label('[string]')	- overrides the label provided in the form.
	read				- Sets the field to read only (does not
						allow input from user.
	onclick('[code]')	- Sets the onclick event handler
	onchange('[code]')	- Sets the onchange event handler
	end([string],[string],...) - value must end with one of the following.

  Notes:
=============================================================================

 The WebSolvers Framework Library may be used and/or modified by anyone owning
 the original work as it was incorporated into an original development project
 so long as this copyright notice and the comments above remain intact.  

 By using this code you agree to indemnify WebSolvers, Inc. from any liability
 that might arise from its use.

 This code may not be sold exclusively or as a part of other code without prior 
 written consent and is expressly forbidden.

 Obtain permission before redistributing this software over the Internet or 
 in any other medium. In all cases the copyright and header must remain intact. 
============================================================================= */

//======================================================================================
//                                 Internal Routines
//======================================================================================

function validateObject() {
	this.typeID = "valid";
	this.labelID = "label";
	this.defaultID = "default";
	
	this.reqField = "_REQ";
	this.reqMessage = "A required field is missing.";

	this.checkField = validateObject_CheckField;
	this.procType = validateObject_ProcType;
	
	this.getType = validateObject_GetType;
	this.getLabel = validateObject_GetLabel;
	this.getDefault = validateObject_GetDefault;
	this.notify = validateObject_Notify;
	
	this.validator = new Array();
	this.addValidator = validateObject_AddValidator;
	this.makeField = validateObject_MakeField;

	this.addValidator('skip', validator_Skip);
		
	this.addValidator('req', validator_Req, null, 2, "'");

	this.addValidator('match', validator_Match, null, 1, "'");

	this.addValidator('join', validator_Join, null, 1, "'");

	this.addValidator('dupe', validator_Dupe, null, 1, "'");

	this.addValidator('label', null, function anonymous(elem, params) {
			elem[validate.labelID] = params[0];
		}, 1, "'");
	
	this.addValidator('read', null, function anonymous(elem, params) {
			elem.readonly = true;
			elem.setEvent("focus", function anonymous(e) { this.blur(); });
		});
	
	this.addValidator('onchange', null, function anonymous(elem, params) {
			var func = null;
			eval("func = function anonymous(e) { " + params[0] + "};");
			elem.setEvent("change", func);
		}, 1, "'");

	this.addValidator('onclick', null, function anonymous(elem, params) {
			var func = null;
			eval("func = function anonymous(e) { " + params[0] + "};");
			elem.setEvent("click", func);
		}, 1, "'");

	this.addValidator('endi', validator_EndI, null, -1, "'");

	this.addValidator('end', validator_End, null, -1, "'");
}

function validateObject_CheckField(field) {
	var fields = null;
	var i = 0;

	if(!field.validate)
		return true;

	if(field.type.substr(0,6).toLowerCase() == "select") {
		field.values = new Array();
		if(field.multiple) {
			for(i = 0; i < field.options.length; i++)
				if(field.options[i].selected)
					field.values.push(field.options[i].value);
		} else if(field.selectedIndex > -1 && field.selectedIndex < field.options.length) {
			field.values.push(field.options[field.selectedIndex].value);
		}
			
		return field.validate();
	} else if(field.type.toLowerCase() == "radio" || field.type.toLowerCase() == "checkbox") {
		fields = field.form.elements[field.name];
		if(fields && fields.length && (fields[0] == field)) {
			field.values = new Array();
			if(field.checked)
				field.values[0] = field.value;
			for(i = 1; i < fields.length; i++) {
				if(!validate.checkField(fields[i]))
					return false;
				if(fields[i].checked)
					field.values.push(fields[i].values[0]);
			}
			return field.validate();
		} else {
			field.values = new Array();
			if(field.checked)
				field.values[0] = field.value;
			return field.validate();
		}
	} else {
		field.values = new Array(field.value);
		return field.validate();
	}
}

function validateObject_ProcType(fld) {
	var type = this.getType(fld);
	var st = 0;
	var lt = -1;
	var pos = 0;
	var str = "";
	var func = null;
	var param = null;
	var preproc = null;
	var tag = null;

	var i = 0;

	fld._valFunc = new Array();
	fld._valParam = new Array();
	
	fld.validate = fieldObject_Validate;
	fld.isValid = fieldObject_IsValid;

	while(st > lt) {
		for(i = 0; i < this.validator.length; i++) {
			tag = this.validator[i];
			if(type.substr(st, tag.tag.length).toLowerCase() == tag.tag) {
				func = tag.func;
				param = new Array();
				preproc = tag.preFunc;
				st += tag.tag.length;
				if(tag.params) {
					if(type.substr(st, 1) == '(') {
						st++;
						while(type.substr(st, 1) != ')' && st < type.length) {
							if(param.length && param.length < tag.param && type.substr(st, 1) == ",")
								st++;
							if(type.substr(st, 1) == tag.paramEsc) {
								st++;
								pos = type.substr(st, type.length).indexOf(tag.paramEsc);
								str = "";
								while(type.substr(st + pos - 1, 1) == '\\' && st + pos < type.length) {
									str += type.substr(st, pos - 1);
									st += pos;
									pos = type.substr(st + 1, type.length).indexOf(tag.paramEsc) + 1;
								}
								param.push(str + type.substr(st, pos));
								st += pos+1;
							} else if(param.length + 1 < tag.params) {
								pos = type.substr(st, type.length).indexOf(',');
								param.push(type.substr(st, pos));
								st += pos+1;
							} else {
								pos = type.substr(st, type.length).indexOf(')');
								param.push(type.substr(st, pos));
								st += pos;
							}
						}
						st++;
					}
				}
				i = tag.tag.length;
			}
		}

		if(func || preproc) {
			if(preproc) {
				preproc(fld, param);
			}
			if(func) {
				fld._valFunc[i = fld._valFunc.length] = func;
				fld._valParam[i] = param;
			}
			
			preproc = null;
			func = null;
			param = null;
		}
		
		lt = st;
		st += type.substr(st, type.length).indexOf('|') + 1;
	}
}

function validateObject_Notify(field) {
	if(field.valError != " ") {
		if(field.type != "hidden" && field.focus)
			field.focus();
		alert(this.getLabel(field, field.valError));
	}
				
	return false;
}

function validateObject_GetType(field) {
	if(field.length && !field.type)
		field = field[0];

	var type = field.getAttribute(this.typeID);

	return (type && type.length ? type : "str");
}

function validateObject_GetLabel(field, msg) {
	if(field.length && !field.type)
		field = field[0];

	var label = field.getAttribute('_' + this.labelID);
	
	if(!label) {
		label = field.getAttribute(this.labelID);

		return (label && label.length ? label : field.name) + msg;
	} else {
		return label;
	}
}

function validateObject_GetDefault(field) {
	if(field.length && !field.type)
		field = field[0];

	var def = field.getAttribute(this.defaultID);

	return (def && def.length ? def : "");
}

function validateObject_AddValidator(tag, func, prefunc, params, paramesc) {
	var idx = this.validator.length;
	var j = 0;
	var idx2 = 0;
	
	var type = new validatorObject(tag, func, prefunc, params, paramesc);
	
	this.validator[idx] = type;
	
	if(validateObject_AddValidator.arguments.length > 5)
		for(j = 5; j < validateObject_AddValidator.arguments.length; j++) {
			idx2 = this.validator.length;
			type = new validatorObject(validateObject_AddValidator.arguments[j], func, prefunc, params, paramesc);
			this.validator[idx] = type;
		}
}

function validatorObject(tag, func, prefunc, params, paramesc) {
	this.tag = tag;
	this.func = func;
	this.preFunc = prefunc;
	this.params = params;
	this.paramEsc = paramesc;
}

function validateObject_MakeField(form, field, type, label, def) {
	var frm = null;
	var fld = null;
	
	if(!form || !form.length)
		return;
	
	frm = document.forms[form];
	if(!frm)
		return;
	
	fld = frm.elements[field];
	
	if(!fld)
		return;
		
	if(dhtml.DOM)
		return;
		
	if(fld.length)
		fld = fld[0];
		
	dhtml.addBasicInit(fld, "fieldObject_MakeValid", label, type, def);
}

function formObject_TmpOnSubmit() {
	alert('Please wait for the page to finish loading before submitting this form.');
	return false;
}

function formObject_Validate() {
	var i = 0;

	for(i = 0; i < this.elements.length; i++)
		if(!validate.checkField(this.elements[i]))
			return false;
	
	return true;
}

function formObject_Lock(strMsg, intSecs) {
	var cmd = "";
	
	if(this._locked) {
		alert(strMsg);
		return false;
	}
	
	this._locked = true;
	cmd = "document.forms[" + this.index + "].unlock();";
	window.setTimeout(cmd, intSecs * 1000);
	
	return true;
}

function formObject_Unlock() {
	this._locked = false;
}

function documentObject_MakeValidForms(doc) {
	var i = 0;
	var j = 0;
	var k = 0;
	var frm = null;
	var field = null;
	var req = null;

	for(i = 0; i < doc.forms.length; i++) {
		dhtml.quickNorm(doc.forms[i], doc);
		doc.forms[i]._onsubmit = doc.forms[i].onsubmit;
		doc.forms[i].onsubmit = formObject_TmpOnSubmit;
	}

	for(i = 0; i < doc.forms.length; i++) {
		frm = doc.forms[i];
		if(!frm.index && frm.index != 0)
			frm.index = i;
		
		req = frm.elements[validate.reqField];
		if(req && req.value && req.value.length) {
			req = req.value.split(',');
			for(i = 0; i < req.length; i++) {
				field = frm.elements[req[i].trim()];
				
				if(field && !field.length && field.name) {
					field[validate.typeID] = "req";
					field['_' + validate.labelID] = validate.reqMessage;
					validate.procType(dhtml.quickNorm(field, doc));
					if(field.validate && !frm.validate)
						frm.validate = formObject_Validate;
				}
			}
		} else {
			for(j = 0; j < frm.elements.length; j++) {
				field = frm.elements[j];

				if(!field.type && field.length) {
					for(k = 0; k < field.length; k++) {
						validate.procType(dhtml.quickNorm(field[k], doc));
						if(field[k].validate && !frm.validate)
							frm.validate = formObject_Validate;
					}
				} else {
					validate.procType(dhtml.quickNorm(field, doc));
					if(field.validate && !frm.validate)
						frm.validate = formObject_Validate;
				}
			}
		}
		if(!frm.lock)
			frm.lock = formObject_Lock;
		if(!frm.unlock)
			frm.unlock = formObject_Unlock;

		frm.onsubmit = frm._onsubmit;
		frm._onsubmit = null;
	}

	return true;
}

function fieldObject_Validate() {
	if(!this.values) {
		alert("'" + this.name + ".validate()' should not be called directly please use '" + this.name + ".form.validate()' instead.");
	}
	if(!this.isValid())
		return validate.notify(this);
	else
		return true;
}

function fieldObject_IsValid() {
	var i = 0;
	var res = null;
	
	this.valError = null;

	for(i = this._valFunc.length-1; i > -1 && !this.valError; i--) {
		res = this._valFunc[i](this.values, this._valParam[i], this);
		if(res[0].length)
			this.valError = res[0];
		this.values = res[1];
	}
	
	return (this.valError == null);
}

function preProc_FieldValidator(tag, params) {
	var name = "";
	var type = "";
	var label = "";
	var def = "";
	
	html = "<INPUT";

	for(var i = 0; i < params.length; i++) {
		switch(params[i][1].toLowerCase()) {
		case "name":
			name = params[i][2];
			html += ' ' + params[i][0];
			break;
		default:
			if(params[i][1].toLowerCase() == validate.typeID)
				type = params[i][2];
			else if(params[i][1].toLowerCase() == validate.labelID)
				label = params[i][2];
			else if(params[i][1].toLowerCase() == validate.defaultID)
				def = params[i][2];
			else
				html += ' ' + params[i][0];
		}
	}

	if(name && name.length && altsrc && altsrc.length)
		dhtml.addBasicInit("doc.forms[].elements['" + name + "']", "fieldObject_MakeValid", "'" + type + "'", "'" + label + "'", "'" + def + "'");

	return html + ">";
}

function fieldObject_MakeValid(type, label, def) {
	dhtml.quickNorm(this);

	this.setAttribute(validate.typeID, type);
	this.setAttribute(validate.labelID, label);
	this.setAttribute(validate.defaultID, def);
}

function validator_Skip(value) {
	var l = new Array();
	for(var j = 0; j < value.length; j++) {
		if(value[j] && value[j].toString().length)
			l[l.length] = value[j];
	}

	return new Array("", l);
}

function validator_Req(value, params, elem) {
	var el = null;
	var val = null;
	
	if(params[0]) {
		el = elem.form.elements[params[0]];
		if(el && params[1]) {
			if(el.isValid())
				val = el.values[0];
			else 
				return new Array(' ', value);
		}
		if(!el || !val || val != params[1])
			return new Array('', value);
	}
	if(!value.length)
		return new Array(' is required.', value);

	for(var i = 0; i < value.length; i++)
		if((!value[i] && value[i] != 0) || !value[i].toString().trim().length)
			return new Array(' is required.', value);
			
	return new Array('', value);
}

function validator_Match(value, params, elem) {
	var el = null;
	var val = null;
	
	if(params[0]) {
		el = elem.form.elements[params[0]];
		if(el) {
			if(el.isValid())
				val = el.values[0];
			else 
				return new Array(' ', value);
		}
	}
	if(!value.length && val.length)
		return new Array(' does not match.', value);

	for(var i = 0; i < value.length; i++)
		if(value[i] != val)
			return new Array(' does not match.', value);
			
	return new Array('', value);
}

function validator_Dupe(value, params, elem) {
	var el = null;
	var val = null;
	
	if(params[0]) {
		el = elem.form.elements[params[0]];
		if(el) {
			if(el.isValid())
				val = el.values[0];
			else 
				return new Array(' ', value);
		}
	}
	value.push(val);
			
	return new Array('', value);
}

function validator_Join(value, params) {
	var j = value.join(params[0]);
	value.length = 0;
	value[0] = j;
	
	return new Array('', value);
}

function validator_End(value, params, elem) {
	var i = 0, j = 0;
	var match = 0;
	var ret = null;
	for(i = 0; i < value.length; i++)
			if(value[i] && value[i].toString().length) {
				match = 0;
				for(j = 0; j < params.length && !match; j++)
					match = (value[i].toString().substring(value[i].length-params[j].length, value[i].length) == params[j]);
					
				if(!match)
					return new Array(' must end with [' + params.join(' or ') + ']', value);
			}
					
	return new Array('', value);
}

function validator_EndI(value, params, elem) {
	var i = 0, j = 0;
	var match = 0;
	var ret = null;
	for(i = 0; i < value.length; i++)
			if(value[i] && value[i].toString().length) {
				match = 0;
				for(j = 0; j < params.length && !match; j++)
					match = (value[i].toString().substring(value[i].length-params[j].length, value[i].length).toLowerCase() == params[j].toLowerCase());
					
				if(!match)
					return new Array(' must end with [' + params.join(' or ') + ']', value);
			}
					
	return new Array('', value);
}

var validate = new validateObject();

if(window.dhtml)
	dhtml.addTag('FORM', null, documentObject_MakeValidForms, null, -1);
