var Validator = function(name, form, errout) {
	this.form   = form;
	$('#'+form).submit(function() {return eval(name+'.validate();');}); 
	this.error  = '';
	this.errout = (errout == undefined) ? null : errout;
	this.values = new Array();
	this.rules  = new Array();
	this.comps  = new Array();
    this.setRules();
}

Validator.prototype.setRules = function() {
	if (ValidatorRules != undefined) {
		this.rules = ValidatorRules;
		return true;
	}
	return false;
}

Validator.prototype.compareValues = function() {
    var num   = arguments.length;
    var buff  = new Array();
        buff[0] = new Array();
        buff[1] = arguments[num-1];;
    for (var i = 0; i < num-1; i++) {
        buff[0].push(arguments[i]);
    }
    this.comps.push(buff);
    return true;
}

Validator.prototype.addValue = function(name, rule, error) {
	this.values.push(new Array(name, rule, error));
	return true;
}

Validator.prototype.addRule = function(name, rule, mode) {
	if (mode != undefined)
		this.rules[name] = new RegExp(rule, mode);
	else 
		this.rules[name] = new RegExp(rule);	
	return true;
}

Validator.prototype.validate = function() {
	var value = '';
	for (var i = 0; i < this.values.length; i++) {
		var elem = $('#'+this.form+' *[@name='+this.values[i][0]+']');
		var type = elem.attr('type'); 
		switch (type) {
			case 'checkbox': 
				var checked = (elem.attr('checked') == undefined) ? false : elem.attr('checked');
				if (checked != this.values[i][1]) this.setError(this.values[i][2]);
			break;
			default :
				value = $('#'+this.form+' *[@name='+this.values[i][0]+']').val();
				value = $.trim(value);
				if (! this.rules[this.values[i][1]].test(value)) this.setError(this.values[i][2]);
				
		}

	}
    if (this.comps.length > 0) {
        for (i = 0; i < this.comps.length; i++) {
            for (j = 0; j < (this.comps[i][0].length - 1); j++) {
                if ($('#'+this.form+' *[@name='+this.comps[i][0][j]+']').val() != $('#'+this.form+' *[@name='+this.comps[i][0][j+1]+']').val()) {
                    this.setError(this.comps[i][1]);
                    break;   
                }
            }
        }
    }
	return this.showError();
}

Validator.prototype.setError = function(error) {
	if (this.errout == null) this.error = this.error + error + "\n";
	else this.error = this.error + error + "<br />";
	return true;
}

Validator.prototype.showError = function() {
	if (this.error == '') return true;
	if (this.errout == null)
		alert(this.error);
	else 
		$('#'+this.errout).html(this.error);
	this.error = '';
	return false;
}

