/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

var validator_flag = true;

var validator_tree = new ExecFn(new JoinFn(new IdGetter(), new SwitchFn({
	"id0":new NameBranch(new And(),{
		"key0":new BoolSeq(new AndAnd(),[
			new IfFn(new JoinFn(new ValueGetter(), new NotEmptyChecker()), new FixFn(true), new MessageValidator("key0 required")),
			new IfFn(new JoinFn(new ValueGetter(), new MinLengthChecker(2)), new FixFn(true), new MessageValidator("key0 min length")),
			new IfFn(new JoinFn(new ValueGetter(), new MaxLengthChecker(4)), new FixFn(true), new MessageValidator("key0 max length"))
		]),
		"key1":new BoolSeq(new AndAnd(),[
			new IfFn(new JoinFn(new ValueGetter(), new NotEmptyChecker()), new FixFn(true), new MessageValidator("key1 required")),
			new IfFn(new JoinFn(new ValueGetter(), new MinLengthChecker(3)), new FixFn(true), new MessageValidator("key1 min length")),
			new IfFn(new JoinFn(new ValueGetter(), new MaxLengthChecker(5)), new FixFn(true), new MessageValidator("key1 max length"))
		])
	}),
	"id1":new NameBranch(new And(),{
		"key0":new BoolSeq(new AndAnd(),[
			new IfFn(new JoinFn(new ValueGetter(), new NotEmptyChecker()), new FixFn(true), new MessageValidator("key0 required")),
			new IfFn(new JoinFn(new ValueGetter(), new MinLengthChecker(4)), new FixFn(true), new MessageValidator("key0 min length")),
			new IfFn(new JoinFn(new ValueGetter(), new MaxLengthChecker(6)), new FixFn(true), new MessageValidator("key0 max length"))
		]),
		"key1":new BoolSeq(new AndAnd(),[
			new IfFn(new JoinFn(new ValueGetter(), new NotEmptyChecker()), new FixFn(true), new MessageValidator("key1 required")),
			new IfFn(new JoinFn(new ValueGetter(), new MinLengthChecker(5)), new FixFn(true), new MessageValidator("key1 min length")),
			new IfFn(new JoinFn(new ValueGetter(), new MinLengthChecker(7)), new FixFn(true), new MessageValidator("key1 max length"))
		])
	})
})));

function checkAndAlert(form){
	if(!validator_flag){
		return true;
	}
	var id = form.getAttribute("action");
	id = id.replace("(.+)\\.[^\\.]+", "$1");
	
	var c = new ValidatorContext();
	c.collectable = new SimpleMessageCollector();
	c.id = id;
	c.inputMap = convertFormToListMap(form);
	var flag = validator_tree.exec(c);
	if(!flag){
		var sb = "";
		for(var i in c.collectable.messageList){
			sb = sb + "\n" + c.collectable.messageList[i];
		}
		alert(sb);
	}
	return flag;
}
