/*
 * FormValidator.js
 *
 * An automatic validator for forms.
 *
 * Written by:
 *	  Odd Möller <odd.moller@cypoint.se>
  *
 * Versions:
 *	  0.9.0    2001-04-10	 OM    Creation.
 *	  1.0.0    2001-09-18	 OM    Redesign.
 *	  1.0.1    2001-09-18	 OM    Few changes
 *    1.0.2    2005-05-30    HA
 *    1.0.3    2005-04-		 POW   Changed emailPattern
 *
 * COPYRIGHT (C) 2001-2005 CYPOINT SYSTEMS INNOVATION AB.
 */

    function validateForm(form, submitButton) {
          // alert("Function validateForm() ");
          var validator = new FormValidator();
          validator.addConstraint(new FormValidator.Constraint("notEmpty", /\w+((\w)*(\s)*)*/, null) );
           if ( validator.validate(form) ) {
                submitButton.disabled = true;
                form.submit();
           }
        }

        function validateFormWithDropDown(form, dropDown, text) {
              // alert("Function validateFormWithDropDown() ");
              var validator = new FormValidator();
              validator.addConstraint(new FormValidator.Constraint("notEmpty", /\w+((\w)*(\s)*)*/, null) );

           if ( validator.validate(form) ) {
                if (dropDown.options[dropDown.selectedIndex].value != "" ) {
                    //submitButton.disabled = true;
                    form.submit();
                } else {
                    alert(text);
                }
           }
        }

        function clearForm(form) {
            // alert("Function clearForm() ");
            for (var i = 0; i < form.elements.length; i++) {
                   var e = form.elements[i];
               if (e.type == "text" || e.type == "checkbox"
                    || e.type == "textarea" ) {
                    form.elements[i].value = "";
                }
            }
        }

        function doNothing() {
            alert("You are in preview mode. The functionality is currently not activated");
        }


// Validator decleration.
function FormValidator() {
	this.constraints = FormValidator.standardConstraints;
}
FormValidator.Constraint = function (name, predicate, formatter) {
	this.name = name;
	this.predicate = predicate;
	this.formatter = formatter || null;
}
FormValidator.Constraint.prototype.getName = function () {
	return this.name;
}
FormValidator.Constraint.prototype.getPredicate = function () {
	return this.predicate;
}
FormValidator.Constraint.prototype.getFormatter = function () {
	return this.formatter;
}
FormValidator.Constraint.prototype.isValid = function (value) {
	var result;
	// Check if the predicate is a RegExp or a Function.
	if (this.predicate.test) {
		// It's a RegExp, so return whether it matches the value or not.
		result = value.match(this.predicate);
	} else {
		// It's a Function, so return whether the return value is true or not.
		result = this.predicate(value) == true;
	}
	return result;
}
FormValidator.Constraint.prototype.format = function (value) {
	return this.formatter(value);
}
FormValidator.prototype.getValue = function (element) {
	return element.value;
}
FormValidator.prototype.setValue = function (element, value) {
	element.value = value;
}
FormValidator.prototype.getConstraint = function (name) {
	return this.constraints[name];
}
FormValidator.prototype.addConstraint = function (constraint) {
	this.constraints[constraint.getName()] = constraint;
}
FormValidator.standardConstraints = {
	"integer": new FormValidator.Constraint("integer", /^[1-9][0-9]*$/),
	"decimal": new FormValidator.Constraint("decimal", /^([1-9][0-9]*)((\.|,)([0-9]+))?$/, function (value, constraint) {
			var str;
			var groups = value.match(constraint.getPredicate());
			if (groups[4] != "") {
				str = groups[1] + "." + groups[4];
			} else {
				str = groups[1];
			}
			return str;
		}),
	"money": new FormValidator.Constraint("money", /^([1-9][0-9]*)((\.|,)([0-9]{2}))?$/, function (value, constraint) {
			var str;
			var groups = value.match(constraint.getPredicate());
			if (groups[4] != "") {
				str = groups[1] + "." + groups[4];
			} else {
				str = groups[1];
			}
			return str;
		}),
	"word": new FormValidator.Constraint("word", /^\S+$/),
	"email": new FormValidator.Constraint("email", /^[\w._-]+@[\w._-]{2,}\.[a-zA-Z]{2,4}$/),
	"telephoneno": new FormValidator.Constraint("telephoneno", /^((((\+[1-9]{1,3})\s*(\(0\))?\s*)|0)[1-9]+)([\/-])?([0-9\s\/-]+)$/, function (value, constraint) {
			var str; // 										 1234			 4	 4	   4	3  2	  11	1  1		   1
			var groups = value.match(constraint.getPredicate());
			if (groups[6] == "/") {
				str = groups[1] + "-" + groups[7];
			} else {
				str = groups[0];
			}
			return str;
		}),
	"postno": new FormValidator.Constraint("postno", /^([A-Z]{1,2}-)?[\d\s]{5,}$/),
	"personalid": new FormValidator.Constraint("personalid", function (value) {
			if (!value.match(/^\d{6}-\d{4}$/))
				return false;
			var sum = 0;
			var odd = true;
			for (var i = 0; i < 10; i++) {
				if (i != 6) {
					var digit = value.charAt(i);
					if (odd)
						sum += 2 * digit;
					else
						sum += 1 * digit;
					odd = !odd;
				}
			}
			return true;
			return (sum % 10) + (1 * value.charAt(10)) == 10;
		}),
	"odd": new FormValidator.Constraint("odd", function (value) {
			return Number(value) % 2 == 1;
		}),
	"even": new FormValidator.Constraint("even", function (value) {
			return Number(value) % 2 == 0;
		})
}
FormValidator.prototype.validate = function (form) {
	for (var i = 0; i < form.elements.length; i++) {
		var element = form.elements[i];
		var value = this.getValue(element);
		var constraint = element.getAttribute("constraint");
		var prompt = element.getAttribute("prompt");
		var constraint = this.getConstraint(constraint);
		if (constraint != null) {
			if (!constraint.isValid(value)) {
				this.handle(element, prompt);
				return false;
			}
			var formatter = constraint.getFormatter();
			var specificFormatter = element.getAttribute("formatter");
			if (specificFormatter != null && specificFormatter != "") {
				eval("formatter = " + element.getAttribute("formatter"));
			}
			if (formatter != null && formatter != "") {
				this.setValue(element, formatter(value, constraint));
			}
		}
	}
	return true;
}
FormValidator.prototype.handle = function (element, prompt) {
	element.focus();
	element.select();
	alert(prompt);
}

