/*
	Some code developed by Peter Wardle
	PO Box 457
	Moss Vale
	NSW 2577
	Australia
	Phone: +61 2 4869 1323
	Fax:   +61 2 4869 2038
	Email: peterw@acenet.com.au

	Example call to ValidateForm()
	------------------------------
	onClick="return ValidateForm('formname','name','Customer Name','R','age','Customer Age','RisNum','email','Email Address','RisEmail');
	first arg				= "name" attribute of the form
	first arg of triplet 	= field name
	second arg of triplet 	= field description (for message reporting)
	third arg of triplet	=	'R' (required) for string type
								'RisEmail' for email type
								'RisDate' for date type (if successful converts date to dd/mm/yyyy format)
								'RisNum' for number type (do not use this for phone numbers)
								'RisNum:min' for number with "min" value
								'RisCurrency' for number type whith 2 decimal places
								'RDecimals4' for number type whith n decimal places
								'RinRange5:8' for a number type in the range of 5 to 8 inclusive
								'RminLength:4' type in at lease 4 characters
								'RinString:abcABC67' only accept characters abcABC67
								'RstdString' only accept standard characters a-z,A-Z,0-9 and space
								'RexclString:*"{]' do not accept characters *"{] (Note: excluded characters must be escaped (rawurlencoded) when passed to this routine)
								'RisPassword' This is a password field and is to be confirmed by 'isConfirm'
								'RisConfirm' This is a password field which confirms 'isPassword'
								'isChecked' Only accept if this check box is checked'
								'notEqual:xxx' Only accept if not equal to "xxx"
								'mustSelect:xxx' Only accept if selection is not equal to "xxx"
*/
/**
*	if this variable is assigned a value it will be appended to the error message
*	this is to give a further explanation to the errors
*/
var form_validate_msg = '';
function ValidateForm() {
	var i,p1,p2,q,description,TestType,min,max;
	var num=0.000;
	var ch,teststr;
	var first=0;
	var firstfield,PWvalue,PWdesc;
	var errors='';
	var str='';
	var error=false;
	var argu=ValidateForm.arguments;
	var args=argu;
	var fieldval,slength;
	if ( args.length == 1 ) {
		// the arguments have been passed as a string and therefore need to be split up
		args = argu[0].split(',');
		for (i=0; i<(args.length); i++) {
			args[i] = args[i].replace(/'/g,"");
		}
	}
	for (i=1; i<(args.length-2); i+=3) {
		// loop through all argument triplets
		// "TestType" is the test condition (eg. RisNum, 3rd parameter in each triplet)
		//alert(args[i]+"\n"+args[i+2]);
		TestType = args[i+2];
		// get this form field object
		o = document.forms[args[0]].elements[args[i]];
		if (o) {
			// it is a form field
			// get the field's description (2nd parameter in each triplet)
			description=args[i+1];
			// find the input value of the field
			fieldval = o.value;
			// get the field length
			slength = o.value.length;
			if (fieldval!="") {
				/*
				if ( fieldval.indexOf('"') != -1 ) {
					errors+='* " character is not allowed in '+description+'.\n';
				}
				*/
				if (TestType.indexOf('isEmail') != -1) {
					p1=o.value.indexOf('@');
					if (p1<1 || p1==(slength-1))
						errors+='Field "'+description+'" must contain an e-mail address.\n';
				}
				if (TestType.indexOf('isDate') != -1) {
					// date format must be (d/m/y)
					// day may be either "d" or "dd"
					// month may be either "m" or "mm"
					// year may be either "yy" or "yyyy"
					// if it is a valid date it will be converted to "dd/mm/yyyy"
					// test for first slash
					error=false;
					p1=o.value.indexOf('/');
					if (p1<1 || p1 >2) {
						errors+='Field "'+description+'" must be in dd/mm/yyyy format.\n';
						error=true;
					} else if (p1==1){
						// pad the field left with a zero
						o.value = "0"+o.value;
						p1++;
					}
					if ( !error ) {
						// first slash is ok
						// test for second slash
						p2=o.value.indexOf('/',p1+1);
						if (p2<4 || p2>5) {
							errors+='Field "'+description+'" must be in dd/mm/yyyy format.\n';
							error=true;
						} else if (p2==4) {
							// the month needs padding left
							o.value = o.value.substr(0,3)+"0"+o.value.substr(3);
						}
					}
					if ( !error ) {
						// second slash is ok
						if ( o.value.length < 8 || o.value.length == 9 ) {
							errors+='Field "'+description+'" must be in dd/mm/yyyy format.\n';
						} else if ( o.value.length == 8 ) {
							// the year needs padding left
							o.value =  o.value.substr(0,6)+"20"+o.value.substr(6);
						}
					}
				}
				if (TestType.indexOf('inString') != -1) {
					// test that each field character is a valid one
					p1=TestType.indexOf(':');
					teststr=TestType.substr(p1+1);
					for ( ch = 0;ch < slength;ch++ ) {
						if ( teststr.indexOf(fieldval.substr(ch,1)) == -1 ) {
							errors+='Only "'+teststr+'" characters are allowed in field "'+description+'".\n';
							break;
						}
					}
				}
				if (TestType.indexOf('stdString') != -1) {
					// test each field character is a standard character
					for ( ch = 0;ch < slength;ch++ ) {
						p2 = fieldval.charCodeAt(ch);
						if ( (p2 < 48 && p2 != 32) || (p2 > 57 && p2 < 65) || (p2 > 90 && p2 < 97) || p2 > 122 ) {
							errors+='Only characters A-Z,a-z and 0-9 and spaces are allowed in field "'+description+'".\n';
							break;
						}
					}
				}
				if (TestType.indexOf('exclString') != -1) {
					// test that each field character is not an excluded one
					p1=TestType.indexOf(':');
					teststr=unescape(TestType.substr(p1+1));
					for ( ch = 0;ch < slength;ch++ ) {
						if ( teststr.indexOf(fieldval.substr(ch,1)) != -1 ) {
							errors+='"'+teststr+'" characters are not allowed in field "'+description+'".\n';
							break;
						}
					}
				}
				if (TestType.indexOf('minLength') != -1) {
					p1=TestType.indexOf(':');
					min=TestType.substr(p1+1);
					if ( o.value.length < min ) {
						errors+='Field "'+description+'" must be at least '+min+' characters long.\n';
					}
				}
				if (TestType.indexOf('isNum') != -1) {
					num = parseFloat(fieldval);
					if (isNaN(fieldval)) {
						errors+='Field "'+description+'" must be numeric.\n';
					}
					if (TestType.indexOf(':') != -1) {
						p1=TestType.indexOf(':');
	          			min=parseFloat(TestType.substr(p1+1));
						if (num<min)
							errors+='Field "'+description+'" must be greater than or equal to '+min+'.\n';
					}
				}
				if (TestType.indexOf('isCurrency') != -1) {
					num = parseFloat(fieldval);
					if (isNaN(fieldval)) errors+='Field "'+description+'" must be numeric.\n';
					p1=fieldval.indexOf('.');
					if (p1 == -1) {
						errors+='Field "'+description+'" must be have a decimal point.\n';
					} else {
						var dec = fieldval.substr(p1+1);
						if ( dec.length != 2 ) errors+='Field "'+description+'" must be have 2 decimal places';
					}
				}
				if (TestType.indexOf('Decimals') != -1) {
					num = parseFloat(fieldval);
					if (isNaN(fieldval)) errors+='Field "'+description+'" must be numeric.\n';
					p1=fieldval.indexOf('.');
					if (p1 == -1) {
						errors+='Field "'+description+'" must be have a decimal point.\n';
					} else {
						p2=TestType.indexOf('Decimals');
	          			min=TestType.substr(p2+8);
						var dec = fieldval.substr(p1+1);
						if ( dec.length != min ) errors+='Field "'+description+'" must be have '+min+' decimal places';
					}
				}
				if (TestType.indexOf('inRange') != -1) {
					num = parseFloat(fieldval);
					if (isNaN(fieldval)) {
						errors+='Field "'+description+'" must be numeric.\n';
					} else {
						p1=TestType.indexOf('inRange');
						p2=TestType.indexOf(':');
	          			min=TestType.substring(p1+7,p2);
	          			max=TestType.substr(p2+1);
						if (num<min || max<num)
							errors+='Field "'+description+'" must be a number between '+min+' and '+max+'.\n';
					}
				}
				if (TestType.indexOf('isPassword') != -1) {
					// this is a password field
					PWvalue = o.value;
					PWdesc = description;
				}
				if (TestType.indexOf('isConfirm') != -1 ) {
					if ( o.value != PWvalue ) {
						// this is a confirm password field
						errors+='"'+PWdesc+'" is not confirmed.\n';
					}
				}
				if (TestType.indexOf('isChecked') != -1) {
					if ( !o.checked ) {
						errors+='Field "'+description+'" must be checked\n';
					}
				}
				if (TestType.indexOf('notEqual') != -1) {
					// test that each field character is a valid one
					p1=TestType.indexOf(':');
					teststr=TestType.substr(p1+1);
					if ( teststr == fieldval ) {
						errors+='"'+fieldval+'" not allowed in field "'+description+'".\n';
					}
				}
				if (TestType.indexOf('mustSelect') != -1) {
					// test that each field character is a valid one
					p1=TestType.indexOf(':');
					teststr=TestType.substr(p1+1);
					if ( teststr == fieldval ) {
						errors+='Field "'+description+'" must be selected.\n';
					}
				}
			} else if (TestType.charAt(0) == 'R')
				errors += 'Field "'+description+'" can not be empty.\n';
		}
		if ( errors && first == 0 ) {
			first = 1;
			firstfield=o;
		}
	}
	if (errors) {
		if ( form_validate_msg != '' ) {
			errors = errors+'\nExplanation:'+form_validate_msg;
			form_validate_msg = '';
		}
		alert('*** FORM VALIDATION WARNING ***\n\n'+errors);
		if ( firstfield.type=="text" || firstfield.type=="textarea" || firstfield.type=="password" ) {
			firstfield.select();
		}
		return false;
	} else {
		return true;
	}
}
function FormDataToPostContent(form_name) {
	var content_to_submit = '';
	var form_element;
	var last_element_name = '';

	for (i = 0; i < document.forms[form_name].elements.length; i++) {
		form_element = document.forms[form_name].elements[i];
		switch (form_element.type) {
 			// Text fields, hidden form elements
 			case 'text':
 			case 'hidden':
 			case 'password':
 			case 'textarea':
 			case 'select-one':
 				content_to_submit += form_element.name + '=' + escape(form_element.value) + '&';
 				break;
			 // Radio buttons
 			case 'radio':
 				if (form_element.checked) {
 					content_to_submit += form_element.name + '=' + escape(form_element.value) + '&';
 				}
 				break;

 			// Checkboxes
 			case 'checkbox':
 				if (form_element.checked) {
 					// Continuing multiple, same-name checkboxes
 					if (form_element.name == last_element_name) {
 						// Strip of end ampersand if there is one
 						if (content_to_submit.lastIndexOf('&') == content_to_submit.length - 1) {
 							content_to_submit = content_to_submit.substr( 0, content_to_submit.length - 1);
 						}
 						// Append value as comma-delimited string
 						content_to_submit += ',' + escape(form_element.value);
 					} else {
 						content_to_submit += form_element.name + '=' + escape(form_element.value);
 					}
 					content_to_submit += '&';
 					last_element_name = form_element.name;
 				}
 				break;
 		}
 	}

 	// Remove trailing separator
 	content_to_submit = content_to_submit.substr(0, content_to_submit.length - 1);
 	return content_to_submit;
 }

function bhAjaxSubmitForm(form_id,div_id,allow_backbutton,validity_check) {
	/* PARAMETERS
		form_id				- string representing the Id of the form to be submitted
		div_id				- string representing the Id of the container to be filled
		allow_backbutton	- boolean true OR false
		validity_check		- string which can be eval'd to true or false
	*/
	formObject = document.getElementById(form_id);
	if ( allow_backbutton ) {
		var bindArgs = {
			formNode: formObject,
			mimetype: "text/html",
			load: function(type, data, evt){
				var fill_data;
				var js_data;
				var pos = data.indexOf('<js>');
				if ( pos == -1) {
					fill_data = data;
				} else {
					// there is some javascript to evaluate
					fill_data = data.substr(0,pos-1);
					js_data = data.substr(pos+10);
					eval(js_data);
				}
				document.getElementById(container_id).innerHTML = fill_data;
				if ( document.forms['form1'] ) {
					for ( var i = 0; i < document.forms['form1'].elements.length; i++ ) {
						var sType = document.forms['form1'].elements[i].type;
						if ( sType == "text" || sType == "textarea" || sType == "file" || sType == "password" ) {
							document.forms['form1'].elements[i].focus();
							break;
						}
					}
				}
				//document.getElementById(div_id).innerHTML = data;
			},
			error: function(t, e) {
				alert("Error!... " + e.message);
			},
		    backButton: function(){
		        // ...and then when the user hits "back", re-show the form
		        formObject.style.display = "";
		        history.go(0);
		    },
		    forwardButton: function(){
		        // and if they hit "forward" before making another request, this
		        // happens:
		        formObject.style.display = "none"; // we don't re-submit
		    },
		    changeURL: true
		};
	} else {
		var bindArgs = {
			formNode: formObject,
			mimetype: "text/html",
			load: function(type, data, evt){
				var fill_data;
				var js_data;
				var pos = data.indexOf('<bhscript>');
				if ( pos == -1) {
					fill_data = data;
				} else {
					// there is some javascript to evaluate
					fill_data = data.substr(0,pos-1);
					js_data = data.substr(pos+10);
					eval(js_data);
				}
				document.getElementById(container_id).innerHTML = fill_data;
				if ( document.forms['form1'] ) {
					for ( var i = 0; i < document.forms['form1'].elements.length; i++ ) {
						var sType = document.forms['form1'].elements[i].type;
						if ( sType == "text" || sType == "textarea" || sType == "file" || sType == "password" ) {
							document.forms['form1'].elements[i].focus();
							break;
						}
					}
				}
				//document.getElementById(div_id).innerHTML = data;
			},
			error: function(t, e) {
				alert("Error!... " + e.message);
			},
		    changeURL: false
		};
	}
	if ( eval(validity_check) ) {
		var request = dojo.io.bind(bindArgs);
	}
	return false;
}
function SetDefaultFocus(FormName) {
	var i,sType;
	for ( i = 0; i < document.forms[FormName].elements.length; i++ ) {
		sType = document.forms[FormName].elements[i].type;
		if ( sType == "text" || sType == "textarea" || sType == "file" || sType == "password" ) {
			document.forms[FormName].elements[i].focus();
			break;
		}
	}
}
function submitForm() {
	var args=submitForm.arguments;
	var i;
	// create parameters for ValidateForm()
	var params = "'"+args[0]+"'";
	for (i=1; i<(args.length); i++) {
		params += ",'"+args[i]+"'";
	}
	if ( args.length == 1 ) {
		document.forms[args[0]].submit();
	} else if (	ValidateForm(params) ) {
		document.forms[args[0]].submit();
	}
}
function submitAjaxForm() {
	var args=submitAjaxForm.arguments;
	var i,response="S";
	// create parameters for ValidateForm()
	var params = "'"+args[0]+"'";
	for (i=1; i<(args.length); i++) {
		params += ",'"+args[i]+"'";
		if ( args[i] == "E" || args[i] == "S" ) {
			response = args[i];
			break;
		}
	}
	var submitit = false;
	if ( args.length == 1 ) {
		submitit = true;
	} else if (	ValidateForm(params) ) {
		submitit = true;
	}
	if ( submitit ) {
		// create parameters for AJAX_runScript
		var parameters = 'a='+document.forms[args[0]].a.value;
		parameters += '&s='+document.forms[args[0]].s.value;
		parameters += '&'+FormDataToPostContent(args[0]);
		AJAX_runScript(document.forms[args[0]].action,parameters,null,response);
	}
}

