/******************************************
 *	Challenger - October 2001
 *	HTML Form Validation functions
 *
 * Checks for empty fields, numerics, 
 * minimum values and valid dates.
 *
 * Added currency and percentage validation functions.
 * Based on those written by R. Colquhoun.  Iestyn, 18/10/2004
 *
 * Added isNotMoreThan function, Iestyn 10/6/2005
 *
 ******************************************* */

var currencyRegex = null;
var percentageRegex = null;
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("\""+o.name.replace(/_/g," ")+"\" field requires a value");			
			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 isNotMoreThan(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," ")+"\" cannot be more than "+d+".");
				isOk = false
			} else {
				isOk = true;
			}
		}else{

			if(o){
				o.focus();
			}
			isOk = false;
		}
	return isOk;
}


/*
 *   This function is duplicated in DateUtils
 *   Yay.  3/8/2004  Iestyn
 */
function _dateLongYearFromShort(twoDigitYearString) {
// Returns four digit year from the supplied two digit value.
// Century assumed is based on a 100 year rolling window based on the current year.
var century;
var twoDigitYear = parseInt(twoDigitYearString);
var thisYear = new Date().getFullYear();
var century_current = parseInt(thisYear.toString().substring(0,2));
var century_previous = century_current - 1;
var lower = parseInt((thisYear - 80).toString().substring(2,5));
var upper = parseInt((thisYear + 20).toString().substring(2,5));

	century = (parseInt(twoDigitYear)>lower&&parseInt(twoDigitYear)<=99)?
		century_previous: century_current;
	century = century.toString();

	return parseInt(century + twoDigitYearString);
}

/*
 *   This function is derived from _dateCompare in DateUtils
 *   25/11/2005 John
 */
// -------------------------------------------------------------------
// _dateCompare (date1,date2)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2 of if they are the same
//   0 if date2 is greater than date1 
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------

function _dateCompare(date1,date2) {
	var d1 = _auDate(date1);
	var d2 = _auDate(date2);
	if (d1== null || d2==null) {
		return -1;
		}
	else if (d1 >= d2) {
		return 1;
		}
	return 0;
}

// Check if date is greater than today 
function isDateGreater(o) {
	return isDateGreater(o,_auDate(Date.toString()));
}

function isDateGreater(o,startDate) {
//
// Note: Use onBlur="isDateGreater(this,'01/01/1900')" event for validating form items
//
var isOk = false;
	if(!(validating==null || validating==o))return false;
	
	if (_dateCompare(o.value, startDate) == 1) {
		isOk = true;
	} else {
		o.focus();
		alert("\""+o.name.replace(/_/g," ")+"\" must be later than " + startDate);
	}
	return isOk;
}

function parseDate(o){
//
// Note: Use onBlur="parseDate(this)" event for validating form items!
//
var isOk = false;
var formattedDate = new String("");
var yearString;

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{1,2})([\/\-])(\d{1,2})([\/\-])(\d{2,4})/, "$3$2$1$4$5");
	yearString = RegExp.$5
	//alert(yearString);
	if (yearString.length < 3) {
		yearString = _dateLongYearFromShort(yearString);
		//alert(yearString);
		str = RegExp.$3 + RegExp.$2 + RegExp.$1 + RegExp.$4 + yearString;
	}
    } 


    var d = new Date(Date.parse(str));
    if(!isNaN(d)){
      var day = d.getDate();
      if (day < 10) day = "0" + day;
      var month = d.getMonth()+1;
      if (month < 10) month = "0" + month;
      yearString = d.getFullYear();
      formattedDate = new String(day+"/"+month+"/"+yearString);
      //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 isValidPhoneNumber(obj){
// Test that form object's value contains a valid phone number by 
// testing that it contains at least 10 digits and permits use of 
// +() and space characters.
var isOk = false;
var clean, str = new String(obj.value);	

	if(str!=null||str!="undefined"){
		clean = str.replace(/[^\d]/g,"");
		if(clean.length<10){
			obj.focus();
		}else{
			// Tidy up phone number by removing any extraneous characters..
			str = str.replace(/\s+/g," "); // Truncate white space.
			obj.value = str.replace(/[^\d\s\(\)\-\+]/g,""); // Allow only these chars.
			isOk = true;
		}
	}
	if(!isOk)
		alert("\""+obj.name.replace(/_/g," ")+"\" must be a valid phone number (Please include area code).");

	return isOk;
}


function validateCurrency(o) {
	if (strEmpty(o.value)) {
		o.value = "$0.00";
		return true;
	} else {
		if (currencyRegex==null) 
			currencyRegex = /^\s*(-)?\$?([0-9,]*)(\.[0-9]{0,2})?\s*$/;
		if (currencyRegex.test(o.value)) {
			o.value = formatCurrency(o.value);				
			return true;
		}
	}
	alert("\"" + o.value + "\" is not a valid currency amount.");
	o.focus();
	o.select();
	return false;
}

		
function validatePercentage(o) {
	if (strEmpty(o.value)) {
		o.value = "0.00%";
		return true;
	} else {
		if (percentageRegex == null)
			percentageRegex = /^\s*(-)?([0-9]*)(\.[0-9]{0,6})?\s*%?\s*$/;
		if (percentageRegex.test(o.value)) {
			o.value = formatPercentage(o.value);
			return true;
		}
	}
	alert("\"" + o.value + " is not a valid percentage.");
	o.focus();
	o.select();
	return false;
}