// Generic Form Validation Routine
// If you do not want password confirmation functionality please pass
// in a 0 for chkPSW. ALSO Must call psw fields Password and Passwordchk to work


var emptymsg = ""
var incorrectmsg = ""
var reWhitespace = /^\s+$/
var reEmail = /^[A-Za-z0-9_\.\-\'&]+\@[A-Za-z0-9\.\-]+\.[A-Za-z]{2,6}$/
var reInteger = /^\d+$/
var reReal = /^[0-9]+\.?[0-9]?[0-9]?$/
var rePhone = /(?:\s|^|:)[\(\)\d\+\- ]*[^#]?\d{5}[\(\)\d\+\- ]*(?:ext|extension)?[:;]?[\(\)\d\+\- ]*(?:\s|$)/
var bpsw 


function validateform(f,chkPSW){

	var e
	var msg = "There are some problems with the data you entered:\n\n";
	var errmsg = "";	
	var em_err = 0 //empty errors
	var in_err = 0 //incorrect errors
	var res
	var d = 0
	var opt, ftype, title, trim
	var bpsw = 0;

	//refresh vars
	emptymsg  = "The following required fields need completion:\n";
	incorrectmsg = "The following fields were completed incorrectly:\n";
	
	for(x=0;x<f.elements.length;x++){
		e = f.elements[x];
		
		opt = "";
		ftype="";
		title="";
		trim="";
		
		//alert(e.name)
		if(e.type=="text" || e.type=="textarea" || e.type=="password" || e.type == "select" || e.type == "select-one" || e.type=="select-multiple"){

			
				
			//Firefox get values for custom attributes from element
			var id = e.id	
			var el = document.getElementById(id);
						
			opt = el.getAttribute("optional");
			ftype = el.getAttribute("ftype");
			title = el.getAttribute("title");
			trim = el.getAttribute("trim");
			
			//uncomment when debugging for details of elements attributes in a msg
			//disp_ElementInfo(e, opt, ftype, title, trim)  

			if(e.type=="text" || e.type=="textarea" || e.type=="password"){									

				//trim any blank spaces before trying to validate data 			
				if(trim!=undefined && trim!=null && trim!="false"){						
					dotrims(e, trim);
				}
	
							
				
				res = validateElement(e.value, opt, ftype, title)
				if(res==1) em_err++ ;
				if(res==2) in_err++ ;			
				if(e.type=="password" && chkPSW==1){ //only do if required
					if(bpsw!=1){ //chk to see if we have already tested matching psws
						if(f.Password.value!=f.PasswordChk.value){
							incorrectmsg = incorrectmsg +" -Your password confirmation did not match your original entry.\n"
							
							in_err ++;
							bpsw = 1; //so we dont do the same for password reconfirmation field
					}
					}
				}

			
			}
			if ((e.type == "select" || e.type == "select-one") && opt=="false"){																

				if ((e.value=="") || (e.value=="Not Entered"))	{
					emptymsg = emptymsg + " -" + title + "\n"
					em_err++					
				}
			}
			if(e.type=="select-multiple" && opt=="false")	{
				
				count = 0;
				opt = e.options;					
				for (var z=0; z<opt.length; z++) 	{ 							
					if (opt[z].selected) {								
						count ++ 		
					} 
				}
								
				if(count==0)	{
					emptymsg = emptymsg + " -" + title + "\n"
					em_err++		
				}
				
			}				
				
		}
		
	}
	if(em_err>0 || in_err>0){
		errmsg = msg
		if(em_err>0){
			errmsg = errmsg + emptymsg + "\n";
			d = 1;
		}
		if(in_err>0){
			errmsg = errmsg + incorrectmsg
			d = 1;
		}		
	}

	
	if(d==1){
		alert(errmsg)
		return false;
	}else{
		return true;
	}
	
}

function dotrims(e, t){
	
	var str = t;
	var code;
	for (var i=0; i<str.length; i++) {
		code = str.substring(i, i+1);
		
		if(code=="l") e.value=LTrim(e.value);
		if(code=="r") e.value=RTrim(e.value);
		if(code=="m") e.value=MTrim(e.value);
	}
	return;
}


function validateElement(val, opt, ftype, title){
	
	var err = 0; //0 = no errors, 1 = empty error, 2 = incorrect data error

	if(opt=="false" && IsEmpty(val)){
		emptymsg = emptymsg + " -" + title + "\n"
		err = 1;
		return err;
	}
	

	switch(ftype){
		case "EMAIL":
			if (!IsEmpty(val) && (isEmail(val)!=true)){
				err = 2;
				incorrectmsg = incorrectmsg + " -" + title + " is not a valid email address.\n";
				break;
			}
			break;
		case "POSTCODE":
			if (!IsEmpty(val) && isUKPostcode(val)!=true){
				err = 2;
				incorrectmsg = incorrectmsg +" -" + title + " is not a valid postcode.\n";
				break;
			}
			break;
		case "INTEGER":
			if (isInteger(val)!=true){
				err = 2;
				incorrectmsg = incorrectmsg +" -" + title + " is not a valid integer.\n";
				break;
			}
			break;
		case "PASSWORD":
			if (val.length<6){
				err = 2;
				incorrectmsg = incorrectmsg +" -" + title + " is less than 6 characters, please enter a password with at least 6 characters in.\n";
				break;
			}
			break;
		case "NUMBER":
			if (!isNumeric(val)){
				err = 2;
				incorrectmsg = incorrectmsg + " -" + title + " is not a number, please enter a numeric value.\n";
				break
			}
			break;
		case "DATE":
			if (!checkdate(val)){
				err = 2;
				incorrectmsg = incorrectmsg + " -" + title + " is not in a correct date format, please enter as dd/mm/yy.\n";
				break
			}
			break;


	}


	return err;		
}




function disp_ElementInfo(e, opt, ftype, title, trim){

	var str =   "element type: " + e.type + "\n"
	str = str + "name: " + e.name + "\n"
	str = str + "value: " + e.value + "\n"
	str = str + "value type: " + ftype + "\n"	
	str = str + "trim: " + trim + "\n"
	str = str + "title: " + title + "\n"
	str = str + "optional: " + opt + "\n"
	
	alert(str)
	
}

function isNumeric(varValue){
	return !isNaN(varValue);
}


function IsEmpty(v){
	return ((v == null) || (v.length == 0) || reWhitespace.test(v));
}

function isPhoneNo(s)
{
	return (rePhone.test(s));
}

function isUKPostcode(strPostcode){
	var pattern = /^[a-zA-Z]{1,2}\d{1,2}[a-zA-Z]?\s*\d[a-zA-Z]{2}$/
	
	return pattern.test(strPostcode);
}

function isEmail(strEmail){
	var pattern=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

	return pattern.test(strEmail);
}

function isInteger(s) {
	return (reInteger.test(s));
}

function isReal(s) {
	return (reReal.test(s));
}


	function checkDateTime(dte){
		//correct format dd/mm/yy hh:mm:ss , dd/mm/yyyy hh:mm:ss, dd/mm/yy, dd/mm/yyyy
		string = dte
		if(string.length > 10){
			if(string.substring(10,11)==" "||string.substring(8,9)==" "){
				if(string.length==17){
					sDate = string.substring(0,8)
					sTime = string.substring(9,17)					
				}else if(string.length==19){
					sDate = string.substring(0,10)
					sTime = string.substring(11,19)
				}
				if(checkdate(sDate) && checktime(sTime)){
					return true;
				}
				
			}
		}else{
			if(checkdate(string)){
				return true;
			}
		}
		return false
		
	}
	
	function checktime(sTime){
		var err = 0
		string = sTime
		var valid = "0123456789:"
		var ok = "yes";
		var tYear, oy
		var temp;
		var b,c,d,e,f
		for (var i=0; i< string.length; i++) {
			temp = "" + string.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") err = 1;
		}
		if (string.length != 8) err=1
		b = string.substring(0, 2) // hour
		c = string.substring(2, 3)// ':'
		d = string.substring(3, 5) // min
		e = string.substring(5, 6)// ':'
		f = string.substring(6, 8) // sec
		if(b<0 || b>23) err=1;
		if(c != ":") err=1;
		if(d<0 || d>59) err=1;
		if(e != ":") err=1;
		if(f<0 || f>59) err = 1;
		
		if(err==1){
			return false;
		}else{
			return true;
		}
		
	}

	function checkdate(dte) { //Checks to British Format dd/mm/yy fails if does not meet
		//Trim blank spaces from before and after the value
		
		var err = 0
		string = dte
		var valid = "0123456789/-"
		var ok = "yes";
		var tYear, oy
		var temp;
		var b,c,d,e,f
		for (var i=0; i< string.length; i++) {
			temp = "" + string.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") err = 1;
		}
		if (string.length != 8 && string.length !=10) err=1
		b = string.substring(3, 5) // month
		c = string.substring(2, 3)// '/'
		d = string.substring(0, 2) // day
		e = string.substring(5, 6)// '/'
		tYear = string.substring(6, string.length) // year
		if(tYear.length==4){
			f = tYear.slice(2,4);			
		}else if(tYear.length==2){
			f = tYear
		}else{
			err = 1
		}

		if (b<1 || b>12) err = 1
		if ((c != '/') && (c != '-')) err = 1
		if (d<1 || d>31) err = 1
		if ((e != '/') && (e != '-'))   err = 1
		if (f<0 || f>99) err = 1
		if (b==4 || b==6 || b==9 || b==11){
			if (d==31) err=1
		}
		if (b==2){
			var g=parseInt(f/4)
			if (isNaN(g)) {
				err=1
			}
		if (d>29) err=1
		if (d==29 && ((f/4)!=parseInt(f/4))) err=1
		}
		if (err==1) {
			return false;
		}else {
			date = string;
			return true;
		}
	}

function makeUSDate(d){
	
	string = d;
	var l = string.length;
	

	if(l==8 || l==10){
		//swap month around with days
		d = string.substring(0,2); //get days
		p1 = string.substring(2,3);//get placeholder
		m = string.substring(3,5); //get month
		p2 = string.substring(5,6);//get placeholder
		y = string.substring(6,l); //get year

		//swap days and month around
		var newD = m + p1 + d + p2 + y
		return newD
	}else{
		return d;
	}	
}

function makeISODate(d){
	
	string = d;
	var l = string.length;
	

	if(l==8 || l==10){
		//swap month around with days
		d = string.substring(0,2); //get days
		p1 = string.substring(2,3);//get placeholder
		m = string.substring(3,5); //get month
		p2 = string.substring(5,6);//get placeholder
		y = string.substring(6,l); //get year

		//swap days and month around
		var newD = y + m + d
		return newD
	}else{
		return d;
	}	
}

function test(){
	alert("hello")
}

