var blnUseDollar = false;
var blnUseParenthesis = false;
var blnUseNegative = false;
//Validates the passed form.
function validateForm(objForm){
	var strValidChars = "";
	//NULL VALIDATION
	if(typeof(valNullFields) != "undefined")
		if(!validateNull(objForm, valNullFields))
			return false;
	//DATE VALIDATION
	if(typeof(valDateFields) != "undefined")
		if(!validateDate(objForm, valDateFields))
			return false;
	//INTEGER VALIDATION
	strValidChars = "0123456789,";
	if(typeof(valIntegerFields) != "undefined")
		if(!validateType(objForm, valIntegerFields, strValidChars, false))
			return false;
	//DECIMAL VALIDATION
	strValidChars = "0123456789.,";
	if(typeof(valDecimalFields) != "undefined")
		if(!validateType(objForm, valDecimalFields, strValidChars, false))
			return false;
	//CURRENCY VALIDATION
	strValidChars = "0123456789.,";
	if(typeof(valCurrFields) != "undefined")
		if(!validateType(objForm, valCurrFields, strValidChars, true))
			return false;
    //EMAIL VALIDATION
	if(typeof(valEmailFields) != "undefined")
		if(!validateEmail(objForm, valEmailFields))
			return false;
    //NULL RADIO VALIDATION
    if(typeof(valRadioFields) != "undefined")
        if(!validateRadio(objForm))
            return false;
	return true;
}
//Validates null fields.
function validateNull(objForm, colValidFields){
    var blnFound;
	for(key in colValidFields){
		var objField = objForm.elements[key];
		if(typeof(objField) != 'undefined'){
		    if(typeof(objField.tagName)=='undefined'){
		        blnFound = false;
		        for(var i=0;i<objField.length;i++){
		            if(objField[i].checked){
		                blnFound = true;
		                break;
                    }
		        }
		        if(!blnFound){
                    alert("Please enter a value for the " + colValidFields[key] + " field.");
				    try{objField[0].focus();}catch(e){}
				    return false;
		        }
		    }else{
			    if(objField.type == "select-one")
				    var strCheck = objField.options[objField.selectedIndex].value;
			    else 
				    var strCheck = objField.value;
			    strCheck = trim(strCheck);
			    if(strCheck == "" || strCheck == "<NULL>"){
				    alert("Please enter a value for the " + colValidFields[key] + " field.");
                    try{objField.focus();}catch(e){}
				    return false;
			    }
			}
		}
	}
	return true;
}
function validateEmail(objForm, colValidFields) {
    //return true;
	for(key in colValidFields){
		var objField = objForm.elements[key];
		if(typeof(objField) != 'undefined'){
			var strCheck = objField.value;
			var regex = /^(\w|')+([-+.](\w|')+)*@(\w|')+([-.](\w|')+)*\.(\w|')+([-.](\w|')+)*$/	
			strCheck = trim(strCheck);
			if(strCheck != "" && !strCheck.match(regex)){
				alert("Please enter a valid email address for the " + colValidFields[key] + " field.");
				return false;
			}
		}
	}
	return true;
}
//Validates fields of the specified type.
function validateType(objForm, colValidFields, strValidChars, blnCurrency){
	var blnValidChar = false;
	resetGlobalVars();
	for(key in colValidFields){
		var objField = objForm.elements[key];
		if(typeof(objField) != 'undefined'){
			if(objField.type == "select-one")
				var strCheck = objField.options[objField.selectedIndex].value;
			else 
				var strCheck = objField.value;	
			for(j = 0; j < strCheck.length; j++){
				var ch = strCheck.charAt(j);
				for(k = 0; k < strValidChars.length; k++){
					if (ch == strValidChars.charAt(k)){
						blnValidChar = true;
						break;
					}
				}
				blnValidChar = checkValidChar(ch, strCheck.length, j, blnValidChar, blnCurrency);
				if(!blnValidChar){
					alert("You have entered an unacceptable character in the " + colValidFields[key] + " field.");
					objField.focus();
					return false;
				}
				blnValidChar = false;
			}
			if(!checkValidString(strCheck)){
				alert("You have entered an invalid string in the " + colValidFields[key] + " field.");
				objField.focus();
				return false;
			}
			if(blnCurrency)
				prepareMoneyField(objField);
		}
	}	
	return true;
}
//Validates date fields.
function validateDate(objForm, colValidFields){
	for(key in colValidFields){
		var objField = objForm.elements[key];
		if(typeof(objField) != "undefined"){
			var dateValue = trim(new String(objForm.elements[key].value));
			if(!validDate(dateValue) && dateValue != ""){
				alert("You have entered an invalid date format in the " + colValidFields[key] + " field.");
				return false;				
			}
		}
	}
	return true;
}
//Checks the specified character to ensure that it is valid.
function checkValidChar(ch, chkStrLength, j, blnValidChar, blnCurrency){
	if((j == 0) && (ch == "$") && (blnCurrency)){
		blnUseDollar = true;
		blnValidChar = true;
	}
	else if((j == 0) && (ch == "-")){
		blnUseNegative = true;
		blnValidChar = true;
	}
	else if((j == 0) && (ch == "(")){
		blnUseParenthesis = true;
		blnValidChar = true;
	}
	else if((j == 1) && (blnUseNegative) && (ch == "$") && (blnCurrency)){
		blnValidChar = true;
	}
	else if((j == 1) && (blnUseDollar) && (ch == "-")){
		blnValidChar = true;
	}
	else if((j == 1) && (blnUseDollar) && (ch == "(")){
		blnUseParenthesis = true;
		blnValidChar = true;
	}
	else if(blnCurrency){
		if((isNaN(ch)) && (j < 3)){
			blnValidChar = true;
		}
		else if((ch == ".") || (ch == ",")){
			blnValidChar = true;
		}
	}
	if((j == (chkStrLength - 1)) && (blnUseParenthesis) && (ch == ")"))
		blnValidChar = true;
	else if((j == (chkStrLength - 1)) && (blnUseParenthesis) && (ch != ")"))
		blnValidChar = false;
	return blnValidChar;
}
//Validates the current string.
function checkValidString(strCheck){
	var arrResults;
	//Check some obvious invalid strings
	if((strCheck == "$") || (strCheck == "-") || (strCheck == "(")  || (strCheck == "."))
		return false;
	else if((strCheck == "-$") || (strCheck == "$-") || (strCheck == "$.") || (strCheck == "()"))
		return false;
	else if((strCheck == "$()") || (strCheck == "(.)"))
		return false;
	//Check if there is more than one decimal
	arrResults = strCheck.match(/\./g);
	if(arrResults != null)
		if(arrResults.length > 1)
			return false;
	//Check for correct formatting of commas
	arrResults = strCheck.match(/,/g);
	if(arrResults != null){
		var arrCommaResults, strValidate, i, j;
		strValidate = strCheck.replace("$", "");
		strValidate = strValidate.replace("-", "");
		strValidate = strValidate.replace("(", "");
		strValidate = strValidate.replace(")", "");
		arrResults = strValidate.split(".");
		for(i = 0; i < arrResults.length; i++){
			if(i == 0){
				arrCommaResults = arrResults[i].split(",");
				for(j = 0; j < arrCommaResults.length; j++){
					if(arrCommaResults[0].length > 3){
						if(!isNaN(arrCommaResults[0].substring(0, 2)))
							return false;
					}
					else if(arrCommaResults[0].length == 0){
						return false;
					}
					else if((j > 0) && (arrCommaResults[j].length != 3)){
						return false;
					}
				}
			}
			else{
				arrCommaResults = arrResults[i].match(/,/g);
				if(arrCommaResults != null)
					return false;
			}
		}
	}	
	return true;
}
//Resets the global variables to false.
function resetGlobalVars(){
	blnUseDollar = false;
	blnUseParenthesis = false;
	blnUseNegative = false;
}
function trim(s){
	var lIndex = 0;
	// Trim left hand side
	for(var i = 0; i < s.length; i++){
		if(s.charAt(i) == " ")
			lIndex = i + 1;
		else
			break;			
	}
	s = s.substring(lIndex, s.length);
	var rIndex = s.length;
	// Trim right hand side
	for(var i = s.length - 1; i > 0; i--){
		if(s.charAt(i) == " ")
			rIndex = i;
		else
			break;
	}
	s = s.substring(0, rIndex);
	return s;
}
function formatPhone(fld){
	/**
	var phone = fld.value;
	var replaceChars = Array("(", ")", "-", " ", ".", ",", "[", "]", "{", "}", "|", ";", ":");
	for(var i = 0; i < replaceChars.length; i++)
		phone = replaceChar(phone, replaceChars[i], "");
	fld.value = phone;
	*/
}
function replaceChar(text, find, repl){
	var strText = new String(text);
	var newText = "";
	for(var i = 0; i < strText.length; i++){
		if(strText.charAt(i) == find)		
			newText += repl;
		else
			newText += strText.charAt(i);
	}
	return newText;	
}
function formatMoney(s, precision){
	var strMoney = trimToNumbers(s);
	if(precision == null) precision = 2;
	if(strMoney != ""){
		var decPos = strMoney.indexOf(".");
		if(decPos == -1)
			strMoney += (precision==2?".00":"")  + (precision==3?".000":"");
		else if(decPos == strMoney.length - 2)
			strMoney += (precision==2?"0":"")  + (precision==3?"00":"");
		else if(decPos == strMoney.length - 1)
			strMoney += (precision==2?"00":"")  + (precision==3?"000":"");
		else if(decPos < strMoney.length -(precision + 1)) {	//trim digit after 2 decimal place
			var digit = strMoney.charAt(decPos + (precision + 1));
			if (parseInt(digit) < 0) { /*skip*/ }
			else if (parseInt(digit) < 5) {
				strMoney = strMoney.substring(0,decPos+(precision + 1));
			} else {
/*----- not working for the case of floating pt rounding issue, rewrited using eval(...).toFixed(...) -----
				var digit2 = strMoney.charAt(decPos + 2);
				strMoney = strMoney.substring(0,decPos+2) + (parseInt(digit2) + 1);
*/
				strMoney = eval(strMoney.substring(0,decPos+(precision + 1)) + (precision==2?" + 0.01":"")  + (precision==3?" + 0.001":"") ).toFixed(precision);
			}
		}
	}
	else{
		return (precision==2?"$0.00":"")  + (precision==3?"$0.000":"");
	}
	// Add commas	
	var strNumbers = strMoney.substring(0, strMoney.indexOf("."));
	var strDecimals = strMoney.substring(strMoney.indexOf(".") + 1, strMoney.length);
	var strReverseNumbers = "";
	var strNewNumbers = "";
	if(strNumbers.length > 3){
		var counter = 1;
		for(var i = strNumbers.length - 1; i > -1; i--){
			strReverseNumbers += strNumbers.charAt(i);
			if(counter % 3 == 0 && i > 0)			
				strReverseNumbers += ",";
			counter++;
		}
		for(var i = strReverseNumbers.length - 1; i > -1; i--)	
			strNewNumbers += strReverseNumbers.charAt(i);
	}
	else{
		strNewNumbers = strNumbers;
	}
	strMoney = "$" + strNewNumbers + "." + strDecimals;
	return strMoney;
}
/**
* Removes all non-numeric characters from the specified string.
*/
function trimToNumbers(value){
	var s = new String(value);
	var retVal = "";
	var arrNumbers = Array("0","1","2","3","4","5","6","7","8","9",".");
	var addChar = false;
	for(var i = 0; i < s.length; i++){
		for(j = 0; j < arrNumbers.length; j++){
			if(s.charAt(i) == arrNumbers[j]){
				retVal += s.charAt(i);
				break;
			}
		}
	}
	return retVal;
}
function unformatMoney(strValue){
	while(strValue.indexOf("$") >= 0)
		strValue = strValue.replace(/\$/, "");
	while(strValue.indexOf(",") >= 0)
		strValue = strValue.replace(/,/, "");
	return strValue;
}
function prepareMoneyField(fld){
	fld.value = trimToNumbers(fld.value);
}
//Rounds number to X decimal places, defaults to 2.
function round(number,X) {
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}
function removeAssArrayItem(a, remKey){
	var b = Array();
	for(key in a){
		if(key != remKey)	
			b[key] = a[key];	
	}
	return b;
}
/*******************************
* Start Date Validation Functions
********************************/
/**
* Validates a string as a date.
* 
* @param dateIn String the date to validate.
* @return True if this is a valid date, otherwise false.
*/
function validDate(/*String*/ dateIn){
	var errMsg = "";
	var arrDate = dateIn.split("/");
	if(arrDate.length!=3)	
		return false;
	var day = arrDate[1];
	var month = arrDate[0];
	var year = arrDate[2];
	if(month.length==2 && month.charAt(0)== '0')		
		month = month.charAt(1);		
	if(day.length==2 && day.charAt(0)== '0')
		day = day.charAt(1);		
	if(arrDate.length != 3)
		return false;
	if(!(isInt(month) && parseInt(month) > 0 && parseInt(month) <= 12 )){
		errMsg = "Not a valid month";
		return false;
	}
	if(!(isInt(year) && parseInt(year) > 1900 && parseInt(year) <= 2100)){
		errMsg = "Not a valid year";
		return false;
	}	
	if(!(isInt(day) && parseInt(day) > 0 && parseInt(day) <= daysInMonth(month, year))){
		errMsg = "Not a valid day";
		return false;
	}
	return true;
}
function isInt(/*String*/ strin){
	var validDigits = "0123456789";
	for(var i = 0; i < strin.length; i++){
		if(validDigits.indexOf(strin.charAt(i)) < 0)
			return false;
	}
	return true;
}
//must take a valid month as String or Int: two digit  01, 02 ...12 or one digit 1,2 ...12
function daysInMonth(/*String*/month, year){
	var m = parseInt(month)
	if(m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10  || m == 12){
		return 31;
	}else if(m == 4 || m == 6 || m == 9 || m == 11){
		return 30;
	}else if(m == 2){
		if(isLeapYear(year))		
			return 29;
		else		
			return 28;	
	}
}
function isLeapYear(/*String*/ year){
	year = year + "";
	if(year.length == 2){
		//placeholder for if we handle 2 digit dates in the future
	}
	if(year.length == 4){
		if((parseInt(year) % 4 == 0) && (!(parseInt(year) % 100 == 0) || (parseInt(year) % 400 == 0)))						
			return true;
	}
	return false;
}
//Validate required radio options.
function validateRadio(objForm){
	if(typeof(valRadioFields) != "undefined"){
		for(key in valRadioFields){
			var objField = objForm.elements[key];
			if(typeof(objField) != 'undefined'){
				if(!isNaN(objField.length)){
					var blnChecked = false;
					for(var j = 0; j < objField.length; j++){
						if(objField[j].checked && (objField[j].type == "radio")){
							blnChecked = true;
						}
					}

					if(!blnChecked){
						alert("Please choose an option for the " + valRadioFields[key] + " field.");
						if(objField.type != "hidden")
							objField[0].focus();
						return false;
					}
				}
			}
		}
		return true;
	}
}
/*******************************
* End Date Validation Functions*
*******************************/

