var Validation = Validation ? Validation : {
	FieldCheck: function (id, div, checks, dependencies){
		this.id = id;
		this.div = div;
		this.checks = checks;
		this.dependencies = dependencies;
		this.checkDependencies = function(){
			if (this.dependancies == null)
				return;
	
			for(i in this.dependencies)
				Validation.fieldCheck(this.dependancies[i], TestCallBack);
		}
		this.clearDependencies = function(){
			for(i in this.dependencies)
				testCallBack(null, this.dependancies[i]);
		}
		this.setFocus = function(){
			document.getElementById(this.id).focus();
			
		}
	},

	getDateObj: function (dateStr){
		var fieldValue = dateStr;
		var e = /^\d{4}-\d\d-\d\d$/
		if (e.test(fieldValue))
			fieldValue = fieldValue.replace(/-/g, "/");
		
		var d = new Date();
		d.setTime(Date.parse(fieldValue));
		if (isNaN(d))
			throw "Date invalid";
		return d;
	},

	checkDate: function (field){
		Validation.getDateObj(field.value);
	},

	checkPassword: function (field){
		if (field.value.length < 8)
			throw "Password needs to be more <br>then 8 characters";
	},
	
	trimField: function(field){
		field.value = field.value.trim();
	},
	
	checkRequired: function(field){
		if (field.value == "")
			throw "Field required";
	},
	
	checkNumeric: function(field){
		var str = field.value;
		for(i =0;i < str.length;i++){
			if (str.charAt(i) < "0" || str.charAt(i) > "9")
				throw "Not a number";
		}
	},
	
	checkForSpaces: function(field){
	
		if (field.value.indexOf(' ') > 0)
			throw "Field cannot contain spaces";
	},
	
	checkEmail: function(field){
		var e = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
		if (!e.test(field.value))
			throw "Please specify a valid email";
	},
	
	checkPhoneNumber: function(field){
		
		var e = /^\+[0-9]+$/
		if (field.value == "")
			return;
		if (!e.test(field.value))
			throw "Phone number must be in <br />international format and contain only <br />numbers (i.e +12345678)";
	},
	
	stripPhoneChars: function(field){
		field.value = field.value.replace(/[\(\- ]/g,"")
	},
	
	fieldCheck: function(fc, callback){
		var element =  document.getElementById(fc.id);
		var i;
		try{
			
			for (i in fc.checks)	
				fc.checks[i](element);

			if (element.value != '')
				fc.checkDependencies();
			else
				fc.clearDependencies();
			callback(null, fc);
			return true;
		}catch(e){

			callback(e, fc);
			return false;
		}

	},

	testCallBack: function(e, fc){
		if (e == null)
			document.getElementById(fc.div).innerHTML="";
		else
			document.getElementById(fc.div).innerHTML=e;
	},

	checkForm: function(arr){
		var ret = true;
		var i;
		try{
			for (i in arr){
				var t = i;
				if (!(Validation.fieldCheck(arr[i], Validation.testCallBack))){
					
					if (ret){
						arr[i].setFocus();
						ret = false;
					}
	
				}
				
			}
		}catch(e){
			ret = false;
		}
		return ret;
	}
}
