/******************************************
 *	Challenger - October 2001
 *	HTML Form Validation functions
 *
 * Checks for empty fields, numerics, 
 * minimum values and valid dates.
  
8< ------------- Snip this usage example out of production code! --------------------------8< 
<html>
<head>
<link rel=StyleSheet href="/Includes/challengergroup.css" type="text/css">
<script src="/Resource/formValidation.js"></script>
<script>
<!--
	function validate(frm) {
	// Check required fields here. NOTE: Field names are CASE-SENSITIVE!
	var ok=true;
		ok=!empty("clientName","clientDOB","funds");
		if(ok) ok=!numeric("funds","assets");
		if(ok) ok=isAtLeast(frm.funds,10000);
		return ok;
	}
//-->
</script>
</head>
<body>
<form action="form2.jsp" method="post" id="form1" onSubmit="return validate(this);">
	<input type="text" name="clientName">
	<input type="text" name="clientDOB" maxlength="10" onBlur="parseDate(this);">
	<input type="text" name="funds">
	<input type="text" name="assets">
	<input type="submit">
</form>
8< ------------- Snip this usage example out of production code! --------------------------8< 

******************************************** */


var validating = null;

function isEmpty(frm) {
var emptyField=false;
	// Test form elements in the supplied form object for empty strings.
	// Returns true if any in the supplied list of form element names is empty.
	// Usage:
	// 		var ok = !isEmpty(document.forms[2],"First_Name","Last_Name");
	//
	//Parse the arguments to the function
	//They represent the names of form elements in the supplied form object "frm"
	for(i=1;i<arguments.length;++i) {
		o=frm.elements[arguments[i]];
		if(o)  { emptyField=strEmpty(o.value);}
		if(emptyField) {
			//o.style.backgroundColor="#ffffcc";
			o.focus();
			alert("Please enter " +"\""+o.name.replace(/_/g," ")+"\" and try again");			
			break;
		}
	}
	return emptyField;
}

function _auDate(str){
// Returns a date object taking into account Australian date format conventions.
// If the supplied date is in the format dd/mm/yy we need to swap
// it around to mm/dd/yy because the Date.parse() method
// will only accept this format.
//
	if(str!=null){
		if(str.match(/^\d+[\/\-\.]\d+/))
			str = str.replace(/^(\d+)([\/\-\.])(\d+)([\/\-\.])/,"$3/$1/");

		var secs=Date.parse(str);
		
		if(!isNaN(secs))
			return new Date(secs);
	}
	return null;
}

function checkDate(o){
// Parse a string and return true if it can be parsed to a valid date.
// Locale aware for AU dd/mm/yy format!
// Can also parse a range of date formats eg.
//  dd-mm-yyyy
//  monday October 1 1989
//  etc. (depending on what can be parsed by JavaScript's Data.parse() )
//
var d = _auDate(o.value);
	if(d==null){
		var fieldName = new String(o.name);
		fieldName = fieldName.replace(/_/g," ");
		alert("Unrecognised date format supplied as \""+fieldName+"\"");
		o.focus();
		return false;
	}else{
		return true;
	}

}

function isValidChar(chr){
// Returns true if a supplied character (actually the first 
// character in the string chr) is found within a list of 
// acceptable characters to be input via a form. (JScript v1 compliant)
var validChars = "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_-+=[]{}|;:'\"<>,.?/`~";
	if(validChars.indexOf(chr.substring(0,1).toLowerCase()) > 0)
		return true;
	else
		return false
}

function strEmpty(str) {
var nonSpaceFound=false,isEmpty=false;

	if(str.length<1 || str=="" || str=="undefined") 
		isEmpty=true;
	if(!isEmpty && str.length > 0){
		nonSpaceFound=false;
		//alert(str+" LENGTH:"+str.length)
		for(var i=0;i<=str.length-1;i++){
			//alert(str+" charAt("+i+"): "+str.charAt(i))
			if(isValidChar(str.charAt(i)))
				nonSpaceFound=true;
		}
		if(nonSpaceFound)
			isEmpty=false;
		else
			isEmpty=true;
	}
	//alert(str+" isEmpty? "+isEmpty)
	return isEmpty;
}

function numeric() {
var nonNumeric=false;
	for(i=0;i<arguments.length;++i) {
		o=document.forms[1].elements[arguments[i]];
		emptyField=strEmpty(o.value);
		if(emptyField) {
			o.value="0";
		} else {
			if(!isNumeric(o)) {
				nonNumeric=true;
				o.focus();
				alert("\""+o.name.replace(/_/g," ")+"\" field requires a numeric value.");
				break;
			}
		}
	}
	return nonNumeric;
}

function isChecked(listOfCheckBoxes) {
// For CheckBoxes.
var isOk = false;
	for(var i=0;i<listOfCheckBoxes.length;i++){
		if(listOfCheckBoxes[i].checked){
			isOk = true;
			break;
		}
	}

	if(!isOk){
		var objectName = new String(listOfCheckBoxes[0].name);
			alert("Please select at least one value for \""+ objectName.replace(/_/g," ")+"\"");
	}
	return isOk;
}

function isNumeric(o) {
var isOk = false;
var str = new String(o.value);	
//alert("["+o.value+"] isNumeric("+str+")")
	if(str!=null||str!="undefined"){
		//Strip out any non-digits $ signs, commas and percentage signs..
		str=str.replace(/[^\d\.]/g,"");
		if(!isNaN(parseFloat(str))){
			o.value=str;
			isOk = true;
		}else{
			o.focus();
			alert("\""+o.name.replace(/_/g," ")+"\" must be a numeric value");
		}
	}
	return isOk;
}


function isAtLeast(o,d) {
var isOk = false;
var val = 0;
		var str = new String(o.value);
		if(isNumeric(o)){
			val = parseFloat(str);
			if(val < d) {
				o.focus();
				alert("\""+o.name.replace(/_/g," ")+"\" must be "+d+" or greater.");
				isOk = false
			} else {
				isOk = true;
			}
		}else{

			if(o){
				o.focus();
			}
			alert("\""+o.name.replace(/_/g," ")+"\" must be a value greater than "+d);
			isOk = false;
		}
	return isOk;
}

function parseDate(o){
//
// Note: Use onBlur="parseDate(this)" event for validating form items!
//
var isOk = false;
var formattedDate = new String("");

if(!(validating==null || validating==o))return false;

  //Get value from component passed in
  str=o.value;


    // If date is in the format dd/mm/yy we need to swap
    // it around to mm/dd/yy because the Date.parse() method
    // will only accept this format.
    if(str.match(/^\d+[\/\-]\d+/)){
      str = str.replace(/^(\d+)([\/\-])(\d+)/,"$3$2$1");
    } 


    var d = new Date(Date.parse(str));
    if(!isNaN(d)){
      var day = d.getDate();
      var month = d.getMonth()+1;
      var year = d.getFullYear();
      formattedDate = new String(day+"/"+month+"/"+year);
      //Set component's value to formattedDate
      o.value=formattedDate;
      validating = null;
      isOk = true;
    }else{
      //Try to set focus back to component
      o.focus();
      validating = o;
      alert("\""+o.name.replace(/_/g," ")+"\" requires a valid date!");
      isOk = false;
    }
    return isOk;
}

function isEmail(o) {
var isOk = false;
var str=new String(o.value);	

	if(str.match(/^[\w_\-\.]+\@[\w_\-]+\.[\w]+/)){
		isOk = true;
	}else{
		o.focus();
		alert("\""+o.name.replace(/_/g," ")+"\" must be a valid e-mail address!");
	}
	return isOk;
}
/*
function findFormItem(statusMessage){
// Find the first text-editable item in any form located on this 
// page and place the cursor there, if found, for convenience.
// CM. 31-01-2002
var i = 0; 
var max;
var name;

for(var j=0;j<document.forms.length;j++){
	name = document.forms[j].name;
	//alert("form "+j+":"+name);
	
	if(name=="quickSearch"||name=="superLinkLogin")
		continue;

	max=document.forms[j].length;
	for(i;i<max;i++){
		if(document.forms[j].elements[i].type == "text" || document.forms[j].elements[i].type == "password"){
			document.forms[j].elements[i].focus();
			break; // get out of loop if the condition is true
		}
	}
	
 }
 
 window.status=statusMessage;
}
*/
