/****************************************************************************************************
Name:
	validateUI.js

Description:
	Provides one point of validation for all form fields. 
	Handles all field types (int, date, etc.)

Functions:
	function removeLeadingSpaces(obj)
	function validateSSN(StrVal, DispName, AllowNulls)
	function validateTaxID(StrVal, DispName, AllowNulls)
	function validateEmail(StrVal, DispName)
	function validateZip(StrVal, DispName, AllowNulls)
	function validateURL(FldObj, DispName, AllowNulls, MaxLength)
	function validatePhone(FldObj, DispName, AllowNulls, Allow7, Allow10, AllowExtra, UseParens)
	function validNumRange(NumVal, Min, Max)
	function validFloatRange(NumVal, Min, Max)
	function validTextLength(StrVal, Min, Max)
	function validTextChars(checkStr, checkOK)
	function invalidTextChars(checkStr, checkOK)
	validateDateRange(obj, minDate, maxDate, displayName, minDisplayName, maxDisplayName, allowNulls)
	function validateField(vObj, vContentType, vDispName, vAllowNulls, vMin, vMax, vMinLength, vMaxLength, vValidChars, vInvalidChars, vCase, vAllowAlphas, vAllowDigits, vAllowOthers)
	function validateMoney(vObj, vDispName, vAllowNulls)
	function strToFloat(amount)

Note:
	The most common uses below use the function validateField as the
	main function, which is intended.  This function should be called
	when validating a field.

Examples:
	Bit:	Checks to make sure field is a bit (0, 1).
			validateField(document.FORNAME.FIELDNAME, 'bit', 'Field Name', [true/false])

	Float:	Checks to make sure field is a float.  
	Money:	Checks to make sure field is a float.
			
			No Min or Max values.
			validateField(document.FORNAME.FIELDNAME, ['float'|'money'], 'Field Name', [true/false], '', '')

			Min value specified.  No Max value.  Maximum can be anything
			validateField(document.FORNAME.FIELDNAME, ['float'|'money'], 'Field Name', [true/false], 100.50, '')

			No Min value.  Specify a maximum value.  Minimum can be anything.
			validateField(document.FORNAME.FIELDNAME, ['float'|'money'], 'Field Name', [true/false], '', 500)

			Both Min and Max values.
			validateField(document.FORNAME.FIELDNAME, ['float'|'money'], 'Field Name', [true/false], 100.50, 500)

	SmallMoney:	Checks to make sure field is a float.
			
			No Min or Max values.  Min & Max values default to -214749 & 214749 respectively.
			validateField(document.FORNAME.FIELDNAME, 'smallmoney', 'Field Name', [true/false], '', '')

			Min value specified.  No Max value.  Maximum defaults to 214749
			validateField(document.FORNAME.FIELDNAME, 'smallmoney', 'Field Name', [true/false], 100.50, '')

			No Min value.  Specify a maximum value.  Minimum defaults to -214749.
			validateField(document.FORNAME.FIELDNAME, 'smallmoney', 'Field Name', [true/false], '', 500)

			Both Min and Max values.
			validateField(document.FORNAME.FIELDNAME, 'smallmoney', 'Field Name', [true/false], 100.50, 500)

			Note:  If Min Max values are outside of the defaults the default values will be used.

	Int:		Checks to make sure field is an integer.  Default values are Min: -2147483648 Max: 2147483648
	SmallInt:	Checks to make sure field is an integer.  Default values are Min: -32768 Max: 32768
	TinyInt:	Checks to make sure field is an integer.  Default values are Min: 0 Max: 255
			
			No Min or Max values.  Min & Max values are set to defaults.
			validateField(document.FORNAME.FIELDNAME, ['int'|'smallint'|'tinyint'], 'Field Name', [true/false], '', '')

			Min value specified.  No Max value.  Maximum is set to default.
			validateField(document.FORNAME.FIELDNAME, ['int'|'smallint'|'tinyint'], 'Field Name', [true/false], 100, '')

			No Min value.  Specify a maximum value.  Minimum is set to default.
			validateField(document.FORNAME.FIELDNAME, ['int'|'smallint'|'tinyint'], 'Field Name', [true/false], '', 200)

			Both Min and Max values.
			validateField(document.FORNAME.FIELDNAME, ['int'|'smallint'|'tinyint'], 'Field Name', [true/false], 100, 200)

			Note:  If Min Max values are outside of the defaults the default values will be used.

			(vObj, vContentType, vDispName, vAllowNulls, vMin, vMax, vMinLength, vMaxLength, vValidChars, vInvalidChars, vCase, vAllowAlphas, vAllowDigits)

	String:	Checks to make sure field is a string.
			There are several more parameters if this is a string, which are described below.

			vMinLength - minimum length of the string
			vMaxLength - maximum length of the string
			vValidChars - used for including any characters, which might otherwise be invalid.  If field should
			              be all alphas, but maybe the digit 1 should be allowed, the vValidChars would be '1'.
			vInvalidChars - any characters in the character set that should not be allowed.
			vCase - 'upper' for uppercase, 'lower' for lowercase, '' for no case change.
			vAllowAlphas - allows alphas to be entered in field.
			vAllowDigits - allows digits to be entered in field.
			vAllowOthers - allows all other characters.

			Min & Max lengths are both set, no extra valid chars, invalid character is 'a', case is upper, alphas are allowed, digits are not allowed
			validateField(document.FORNAME.FIELDNAME, 'string', 'Field Name', false, '', '', 5, 50, '', 'a', 'upper', true, false)

			Max length is set, extra char is '1', no invalid characters, no case is set, alphas are allowed, digits are not allowed
			validateField(document.FORNAME.FIELDNAME, 'string', 'Field Name', false, '', '', '', 50, '1', '', '', true, false)

			Min length is set, extra char is 'a', no invalid characters, no case is set, alphas are not allowed, digits are allowed
			validateField(document.FORNAME.FIELDNAME, 'string', 'Field Name', false, '', '', 5, '', 'a', '', '', false, true)

	Date:	Checks to make sure field is really a date.  Default values are Min: 01/01/1900 Max: 12/31/9999
			
			No Min or Max values.  Min & Max values are set to defaults.
			validateField(document.FORNAME.FIELDNAME, ['datetime'], 'Field Name', [true/false], '', '')

			Min value specified.  No Max value.  Maximum is set to default.
			validateField(document.FORNAME.FIELDNAME, ['datetime'], 'Field Name', [true/false], '01/01/1995', '')
			validateField(document.FORNAME.FIELDNAME, ['datetime'], 'Field Name', [true/false], document.FRMNAME.STARTDATEFIELD.value, '')

			No Min value.  Specify a maximum value.  Minimum is set to default.
			validateField(document.FORNAME.FIELDNAME, ['datetime'], 'Field Name', [true/false], '', '01/01/2005')
			validateField(document.FORNAME.FIELDNAME, ['datetime'], 'Field Name', [true/false], '', document.FRMNAME.ENDDATEFIELD.value)

			Both Min and Max values.
			validateField(document.FORNAME.FIELDNAME, ['datetime'], 'Field Name', [true/false], '01/01/1995', '01/01/2005')
			validateField(document.FORNAME.FIELDNAME, ['datetime'], 'Field Name', [true/false], document.FRMNAME.STARTDATEFIELD.value, document.FRMNAME.ENDDATEFIELD.value)

			Note:  If Min Max values are outside of the defaults the default values will be used.
****************************************************************************************************/
//Trim left and right spaces and tabs
function Trim(s) {
	//trim off left spaces/tabs
	for(var i=0; i<s.length; i++) {
		if((s.charAt(i)!=' ')&&(s.charAt(i)!='\t')) break;
	}
	s = s.substring(i, s.length);

	//trim off right spaces/tabs
	for(var i=s.length-1; i>=0; i--) {
		if((s.charAt(i)!=' ')&&(s.charAt(i)!='\t')) break;
	}
	
	return s.substring(0, i+1);
}


//use this function to verify a valid tax id. TaxID should be in the form:
// 999999999		(9 digits)
// 333-22-4444		(3 digits, dash, 2 digits, dash, 4 digits)
function validateSSN(StrVal, DispName, AllowNulls) {
	var ssnexpr = /^\d{9}$|^\d{3}\-\d{2}\-\d{4}$/
	var bRetVal = false;
	var sValue = StrVal.value;

	if(AllowNulls && (sValue.length==0)) {
		return true;
	}
	
	bRetVal = ssnexpr.test(sValue);

	if (bRetVal == false) {
		alert ('Please enter a valid SSN [######### or ###-##-####] for ' + DispName + '.');
	}

	if(sValue.indexOf('-',0)==-1 && (sValue.length>0)) {
		StrVal.value = sValue.substring(0,3) + '-' + sValue.substring(3,5) + '-' + sValue.substring(5,9);
	}
	
	return bRetVal;
}

//use this function to verify a valid tax id. TaxID should be in the form:
// 999999999		(9 digits)
// 22-7777777		(2 digits, dash, 7 digits)
// 333-22-4444		(3 digits, dash, 2 digits, dash, 4 digits)
function validateTaxID(StrVal, DispName, AllowNulls) {
	var taxexpr = /^\d{9}$|^\d{2}[\-]\d{7}$|^\d{3}[\-]\d{2}[\-]\d{4}$/
	var bRetVal = false;
	var sValue = StrVal.value;
	if(AllowNulls && (sValue.length==0)) {
		return true;
	}
	
	bRetVal = taxexpr.test(sValue);

	if (bRetVal == false) {
		alert ('Please enter a valid TaxID [######### or ##-####### or ###-##-####] for ' + DispName + '.');
	}

	return bRetVal;
}


//use this function to verify valid email address
function validateEmail(FldObj, DispName, AllowNulls) {
	var emailexp = /^[a-z_0-9][a-z_0-9\-\.\']+@[a-z_0-9-\.]+\.[a-z]{2,4}$/i
	var bRetVal = false;
	var sValue = FldObj.value;
	
	if((sValue.length==0) && AllowNulls) return true;

	bRetVal = emailexp.test(sValue);

	if (bRetVal == false) {
		alert ('Please enter a valid email address for ' + DispName + '.');
	}

	return bRetVal;
}

//use this function to verify valid zipcodes
function validateZip(StrVal, DispName, AllowNulls) {
	var zipexpr = /^\d{5}$|^\d{5}[\-\s]?\d{4}$/
	var bRetVal = false;
	var sValue = StrVal.value;
	
	if(AllowNulls && (sValue.length==0)) {
		return true;
	}
	
	bRetVal = zipexpr.test(sValue);

	if (bRetVal == false) {
		alert ('Please enter a valid zip code for ' + DispName + '.');
	}

	if((sValue.indexOf('-',0)==-1) && (sValue.length > 5)) {
		StrVal.value = sValue.substring(0,5) + '-' + sValue.substring(5,9);
	}

	return bRetVal;
}

//use this function to verify valid url
function validateURL(FldObj, DispName, AllowNulls, MaxLength) {
	var bRetVal = false;
	bRetVal = validateField(FldObj, 'string', DispName, AllowNulls, '', '', 1, MaxLength, '-:./?=%&_', ' ', 'none', true, true);

	if (bRetVal == true) {
		var sURL = FldObj.value;
		var sNewURL = '';

		if (sURL.length > 0) {
			if( (sURL.substr(0, 7) != 'http://') &&
				(sURL.substr(0, 8) != 'https://') &&
				(sURL.substr(0, 6) != 'ftp://') ) {
				sNewURL = 'http://' + sURL;
				FldObj.value = sNewURL;						
			}
		}
	}

	return bRetVal;
}

//use this function to verify valid phone
//When AllowExtra is true, any characters after the first 7 or 10 digits are allowed. They will
//	be kept as-is, with a single space between the last digit and the first Extra character
//When UseParens is true, a 10-digit number will be formatted as "(xxx) xxx-xxxx" instead of the default "xxx-xxx-xxxx"
//
//NOTE: AllowNulls, Allow7, Allow10, and AllowExtra ALL default to true and do not need to be passed
//		UseParens defaults to false and does not need to be passed.
function validatePhone(FldObj, DispName, AllowNulls, Allow7, Allow10, AllowExtra, UseParens) {
	var sValue = Trim(FldObj.value);						//The working value, based on the original text value
	var bFirst = true;										//bFirst is true until the first non-"1" digit has been found
	var sNumbers = '';										//Temporarily stores the first 7 or 10 digits found, excluding any leading 1's
	var lLastNumIndex = 0;									//The index of the last found digit (the 7th or 10th) in sValue. Used for truncating extra chars
	var bAllow7 = (Allow7==false ? false : true);			//Only if the parameter is false should we
	var bAllow10 = (Allow10==false ? false : true);			//set the bVal to false. Otherwise the
	var bAllowExtra = (AllowExtra==false ? false : true); 	//"default" of true will take effect.
	var bAllowNulls = (AllowNulls==false ? false : true);
	var bUseParens = (UseParens==true ? true : false);		//Same as above, but the default is false
	var sExtraVals = '';									//Everything to the right of the first 7/10 digits
	var sFormatMessage;
	
	if(bAllow7 && bAllow10)
		sFormatMessage = 'Please enter a number in ' + DispName + ' in the following format: ###-#### or ###-###-####';
	else if (bAllow7) 
		sFormatMessage = 'Please enter a number in ' + DispName + ' in the following format: ###-####';
	else
		sFormatMessage = 'Please enter a number in ' + DispName + ' in the following format: ###-###-####';
		
	if((!bAllow7) && (!bAllow10)) {
		alert('Programming error! validatePhone must have Allow7 or Allow10 set to true!');
		return false;
	}
	
	if (sValue.length>0) {
		//Get the first 7 or 10 digits (the first digit can NOT be 1)
		for (i=0; i<sValue.length; ++i) {
			if(isnumeric(sValue.charAt(i))) {
				//Ignore any and all leading 1's
				if(bFirst) {
					if(sValue.charAt(i)!='1') {
						bFirst = false;
						sNumbers+=sValue.charAt(i);
						lLastNumIndex = i;
					}
				}
				else {
					sNumbers+=sValue.charAt(i);
					lLastNumIndex = i;
					
					//Break at 7 or 10 digits.
					if(!bAllow10&&(sNumbers.length==7)) break;
					if(sNumbers.length==10) break;
				}
			}
		}
		
		//Store the extra data (anything after the first 7/10 digits)
		sExtraVals = sValue.substring(lLastNumIndex+1, sValue.length);
		if(sExtraVals.length>0) {
			if(!bAllowExtra) {
				//Extra characters besides the digits were put in, but not allowed
				alert(sFormatMessage);
				return false;
			}
			
			//Format the extra values
			sExtraVals = ' ' + Trim(sExtraVals);
		}
		
		//If the number has 10 digits, format it
		if((bAllow10) && (sNumbers.length==10)) {
			if(bUseParens) {
				FldObj.value = '(' + sNumbers.substring(0,3) + ') ' + sNumbers.substring(3,6) + '-' + sNumbers.substring(6,10) + sExtraVals;
			}
			else {
				FldObj.value = sNumbers.substring(0,3) + '-' + sNumbers.substring(3,6) + '-' + sNumbers.substring(6,10) + sExtraVals;
			}
			return true;
		}
		else if ((bAllow7) && (sNumbers.length==7)) {
			FldObj.value = sNumbers.substring(0,3) + '-' + sNumbers.substring(3,7) + sExtraVals;
			return true;
		}
		else {
			//Not 7 or 10 digits or the number they entered is not allowed
			alert(sFormatMessage);
			return false;
		}
	}
	else if(bAllowNulls==false) {
		alert('Please enter a value in ' + DispName + '.');
		return false;
	}
	
	return true;
}

//use this function to verify ranges for number fields
function validNumRange(NumVal, Min, Max) {
    if (parseInt(NumVal) < Min && Min != '') {
        return false;
    }

    if (parseInt(NumVal) > Max && Max != '') {
        return false;
    }

    return true;
}

//use this function to verify ranges for number fields
function validFloatRange(NumVal, Min, Max) {
    if (parseFloat(NumVal) < Min && Min != '') {
        return false;
    }

    if (parseFloat(NumVal) > Max && Max != '') {
        return false;
    }

    return true;
}

//use this function from to verify the length of text fields
function validTextLength(StrVal, Min, Max) {
    if (StrVal.length < Min && Min != '') {
        return false;
    }
    if (StrVal.length > Max && Max != '') {
        return false;
    }

    return true;
}

//use this function from to verify valid text characters
function validTextChars(checkStr, checkOK) {
	var allValid = true;
	var ch = '';

	for (var i = 0; i < checkStr.length;  i++) {
		ch = checkStr.charAt(i);
		
		for (var j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
			break;

		if (j == checkOK.length) {
			allValid = false;
			break;
		}
	}

    return allValid;
}

//use this function from to verify invalid text characters
function invalidTextChars(checkStr, checkNOTOK) {
	var allValid = true;
	var ch = '';

	for (var i = 0;  i < checkStr.length;  i++) {
		ch = checkStr.charAt(i);

		for (var j = 0;  j < checkNOTOK.length;  j++)
		{
			if (ch == checkNOTOK.charAt(j))
			{
				break;
			}
		}

		if (j != checkNOTOK.length) 
		{
			allValid = false;
			break;
		}
	}

	return allValid;
}

//modify by hemant kumar,according to the given datetime format  
//use this function from to verify ranges for date fields
function validDateRange(DTVal, Min, Max) 
{
	if (Min != '') 
	{
		var dtMin = new Date(Min);

		if (dtMin == 'NaN') { return false; }
//code added if min value is passed
	var DayPosition;
	var MonthPosition;
	var YearPosition;
    var sdtDay = '0';
    var sdtMonth = '0';
    var sdtYear = '0';
    var sminDay = '0';
    var sminMonth = '0';
    var sminYear = '0';

	DayPosition = dateFormat.indexOf("d",0);
	MonthPosition = dateFormat.indexOf("m",0);
	YearPosition = dateFormat.indexOf("y",0);
	
	var arrdt=new Array();	
	arrdt= DTVal.split("/");
	
	sdtDay = arrdt[DayPosition];
	sdtMonth = arrdt[MonthPosition];
	sdtYear = arrdt[YearPosition];
    var arrmin=new Array();	
	arrmin= Min.split("/");
	
	sminDay = arrmin[DayPosition];
	sminMonth = arrmin[MonthPosition];
	sminYear = arrmin[YearPosition];    
      //comparing year       
      if (Number(sdtYear) > Number(sminYear))
        {
            return true;
        }
       if (Number(sdtYear) < Number(sminYear))
        {  
		    return false;
		}        
        //if years are equal, comparing months and days
        if (Number(sdtYear) == Number(sminYear))
        {
            if(Number(sdtMonth) > Number(sminMonth))
            {
                return true;
            }
            if(Number(sdtMonth) < Number(sminMonth))
            {
                return false;
            }
     
            
            if(Number(sdtMonth) == Number(sminMonth))
            {
                if(Number(sdtDay) > Number(sminDay))
                {             
                    return true;
                }   
                if(Number(sdtDay) < Number(sminDay))
                {
                    return false;    
                }    
                if(Number(sdtDay) == Number(sminDay))
                {
                    return true;    
                }    
                
             }    
         }
         //code addition end
    	      	
	}

	if (Max != '') {
		var dtMax = new Date(Max);

		if (dtMax == 'NaN') { return false; }

		//code added for the case if Max value is passed		
 
    var DayPosition;
	var MonthPosition;
	var YearPosition;
    var sdtDay = '0';
    var sdtMonth = '0';
    var sdtYear = '0';
    var smaxDay = '0';
    var smaxMonth = '0';
    var smaxYear = '0';
    
	DayPosition = dateFormat.indexOf("d",0);
	MonthPosition = dateFormat.indexOf("m",0);
	YearPosition = dateFormat.indexOf("y",0);
	
	var arrdt=new Array();	
	arrdt= DTVal.split("/");
	
	sdtDay = arrdt[DayPosition];
	sdtMonth = arrdt[MonthPosition];
	sdtYear = arrdt[YearPosition];
     
    var arrmax=new Array();	
	arrmax= Max.split("/");
	
	smaxDay = arrmax[DayPosition];
	smaxMonth = arrmax[MonthPosition];
	smaxYear = arrmax[YearPosition];
    

      //comparing year       
      if (Number(sdtYear) > Number(smaxYear))
        {
            return false;
        }
       if (Number(sdtYear) < Number(smaxYear))
        {  
            return true;
        }
        
        //if years are equal, comparing months and days
        if (Number(sdtYear) == Number(smaxYear))
        {
           
            if(Number(sdtMonth) > Number(smaxMonth))
            {
                return false;
            }
            if(Number(sdtMonth) < Number(smaxMonth))
            {
                return true;
            }
     
            
            if(Number(sdtMonth) == Number(smaxMonth))
            {
                
                if(Number(sdtDay) > Number(smaxDay))
                {
		    return false;
		}
                if(Number(sdtDay) < Number(smaxDay))
                {
                    return true;    
                }    
                if(Number(sdtDay) == Number(smaxDay))
                {
                    return true;    
                }    
                
             }    
         }
	
//code addition end
		
	}

	return true;
}

function stringReplace(originalString, findText, replaceText) {
	var pos=0;
	var len=findText.length;
	var preString;
	var postString;
	
	pos = originalString.indexOf(findText)
	while (pos!=-1) {
		preString = originalString.substring(0, pos);
		postString = originalString.substring(pos + len, originalString.length);
		originalString = preString + replaceText + postString;
		pos = originalString.indexOf(findText, pos + replaceText.length);
	}
	
	return originalString;
}

//this is the main validate function
function validateField(vObj, vContentType, vDispName, vAllowNulls, vMin, vMax, vMinLength, vMaxLength, vValidChars, vInvalidChars, vCase, vAllowAlphas, vAllowDigits, vAllowOthers) {
	var vMinRange = 0;
	var vMaxRange = 0;
	var sValue = vObj.value;
	var sDigits = '0123456789';
	var sAlphas = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	var sOthers = '`~!@#$%^&*()-_=+[{]}\\|;:\'\",<.>/?\n\r';
	var sTemp = '';

	if (vValidChars == null) vValidChars = '';	
	if (vInvalidChars == null) vInvalidChars = '';	
	
	var i;
	var hadChar = false;
	
	//first check the allow nulls
    if (sValue.length == 0) {
        if (vAllowNulls == false) {
             window.alert('Please enter a value in ' + vDispName + '.');
             vObj.focus();
             return false;
        }

		return true;
    }
	else {
		//check any blank or return chars
		for (i = 0; i < sValue.length; ++i) {
		    var ch = sValue.charAt(i);

		    if (ch == ' ' || ch == '\t') {
		        //if (vAllowNulls == false) {
		             //window.alert('Please enter a value in ' + vDispName + '.');
		             //vObj.focus();
		             //return false;
		        //}

		        //return true;
		    }
		    else {
				hadChar = true;
				break;
		    }
		}

		//added to alert to blank values, but not leading blank values
		if (vAllowNulls == false) {
			if (hadChar == false) { 
				window.alert('Please enter a value in ' + vDispName + '.');
				vObj.focus();
				return false;
			}
		}
	}

	//now check values
	switch(vContentType) {
		case 'bit':

			if (sValue != 1 && sValue != 0) {
			    window.alert('Please enter a boolean value in ' + vDispName + '.');
			    vObj.focus();
			    return false;
			}

			break;
		
		case 'float':

			if (parseFloat(sValue) != sValue) {
			    window.alert('Please enter a number in ' + vDispName + '.');
			    vObj.focus();
			    return false;
			}

			if (validFloatRange(sValue, vMin, vMax) == false) {
				window.alert('Please enter a number between ' + vMin + ' and ' + vMax + ' in ' + vDispName + '.');
				vObj.focus();
				return false;
			}

			break;

		case 'money':

			if (parseFloat(sValue) != sValue) {
			    window.alert('Please enter a number in ' + vDispName + '.');
			    vObj.focus();
			    return false;
			}

			if (validFloatRange(sValue, vMin, vMax) == false) {
				window.alert('Please enter a number between ' + vMin + ' and ' + vMax + ' in ' + vDispName + '.');
				vObj.focus();
				return false;
			}

			break;

		case 'smallmoney':
			
			vMinRange = -214749;
			vMaxRange = 214749;

			if (parseFloat(sValue) != sValue) {
			    window.alert('Please enter a number in ' + vDispName + '.');
			    vObj.focus();
			    return false;
			}

			//get min and max ranges
			vMin = (vMin == '' || vMin < vMinRange) ? vMinRange : vMin;
			vMax = (vMax == '' || vMax > vMaxRange) ? vMaxRange : vMax;

			if (validFloatRange(sValue, vMin, vMax) == false) {
				window.alert('Please enter a number between ' + vMin + ' and ' + vMax + ' in ' + vDispName + '.');
				vObj.focus();
				return false;
			}

			break;

		case 'int':

			vMinRange = -2147483648;
			vMaxRange = 2147483647;

            if (Number(sValue) != sValue) {
                window.alert('Please enter a whole, integer number in ' + vDispName + '.');
                vObj.focus();
                return false;
            }

			//get min and max ranges
			vMin = (vMin == '' || vMin < vMinRange) ? vMinRange : vMin;
			vMax = (vMax == '' || vMax > vMaxRange) ? vMaxRange : vMax;

            if (validNumRange(sValue, vMin, vMax) == false) {
				window.alert('Please enter a number between ' + vMin + ' and ' + vMax + ' in ' + vDispName + '.');
				vObj.focus();
				return false;
            }

			break;

		case 'smallint':

			vMinRange = -32768;
			vMaxRange = 32768;

            if (Number(sValue) != sValue) {
                window.alert('Please enter a whole, integer number in ' + vDispName + '.');
                vObj.focus();
                return false;
            }

			//get min and max ranges
			vMin = (vMin == '' || vMin < vMinRange) ? vMinRange : vMin;
			vMax = (vMax == '' || vMax > vMaxRange) ? vMaxRange : vMax;

            if (validNumRange(sValue, vMin, vMax) == false) {
				window.alert('Please enter a number between ' + vMin + ' and ' + vMax + ' in ' + vDispName + '.');
				vObj.focus();
				return false;
            }

			break;

		case 'tinyint':

			vMinRange = 0;
			vMaxRange = 255;

            if (Number(sValue) != sValue) {
                window.alert('Please enter a whole, integer number in ' + vDispName + '.');
                vObj.focus();
                return false;
            }

			//get min and max ranges
			vMin = (vMin == '' || vMin < vMinRange) ? vMinRange : vMin;
			vMax = (vMax == '' || vMax > vMaxRange) ? vMaxRange : vMax;

            if (validNumRange(sValue, vMin, vMax) == false) {
				window.alert('Please enter a number between ' + vMin + ' and ' + vMax + ' in ' + vDispName + '.');
				vObj.focus();
				return false;
            }

			break;

		case 'phone':
			//Don't worry about blank fields - they're covered above
			var numdigits=0;
			var sTrimValue='';
			
			//See how many digits are in our number
			for (i=0; i<sValue.length; ++i) {
				if (isnumeric(sValue.charAt(i))) numdigits++;
			}
			
			if ((numdigits<10) || (numdigits>11)) {
				window.alert('Please enter a valid phone number in the form of ###-###-####.');
				vObj.focus();
				return false;
			}
			
			return true;
				
			break;

		case 'string':

			if (validTextLength(sValue, vMinLength, vMaxLength) == false) {
				window.alert('Please enter at least ' + vMinLength + ' character(s) and at most ' + vMaxLength + ' character(s) in ' + vDispName + '.');
				vObj.focus();
				return false;
			}

			//convert to lower or upper if needed
			if (vCase == 'lower') { sValue = sValue.toLowerCase(); }
			if (vCase == 'upper') { sValue = sValue.toUpperCase(); }
			vObj.value = sValue;

			//add to valid chars, alphas & numbers id needed
			if (vAllowAlphas == true) { vValidChars = vValidChars + sAlphas; }
			if (vAllowDigits == true) { vValidChars = vValidChars + sDigits; }
			if (vAllowOthers == true) { vValidChars = vValidChars + sOthers; }

			//check for valid chars sent in
			if (vValidChars != '') {
				if (validTextChars(sValue, vValidChars) == false) {
					//sTemp = vValidChars.substring(0, vValidChars.indexOf(' ')-1) + '{space}' + vValidChars.substring(vValidChars.indexOf(' '), vValidChars.length);
					sTemp = stringReplace(vValidChars, ' ', '{space}');
					window.alert('Invalid character(s) were entered in ' + vDispName + '. The following character(s) are valid: ' + sTemp);
				    vObj.focus();
					return false;
			    }
			}

			//check for invalid chars sent in
			if (vInvalidChars != '') {
			    if (invalidTextChars(sValue, vInvalidChars) == false) {
					window.alert('Invalid character(s) were entered in ' + vDispName + '. The following character(s) are not valid: ' + vInvalidChars);
					vObj.focus();
					return false;
			    }
			}

			break;

		case 'datetime':
		
            var sTmpVal = sValue;
            var iFirst = 0;
            var iLast = 0;
            var sDay = '0';
            var sMonth = '0';
            var sYear = '0';
			var lDayMax = 0;

			/*    
			//run a couple of quick checks to make sure the date is at least semi-valid
			//check the lengths to make sure format is either MM/DD/YYY or M/D/YYYY
			if ((sTmpVal.length < 8) || (sValue.length > 10)) {
				window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
				vObj.focus();
				return false;
			}
			else {
				//do a quick check to make sure the date is even a date
				var vValidDate = new Date(sValue);

				if (vValidDate == 'NaN') {
					window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
					vObj.focus();
					return false;
				}
			}
			*/

			//do a quick check to make sure the date is even a date
			var vValidDate = new Date(sValue);

			if (vValidDate == 'NaN') {
				window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
				vObj.focus();
				return false;
			}

			//now check the slashes to see if they are in the right places
			//for ease of use, convert dashes into slashes
		    //and check location of slashes
			sTmpVal = sTmpVal.replace('-', '/')
			sTmpVal = sTmpVal.replace('-', '/')
			vObj.value = sTmpVal;
    
            iFirst = sTmpVal.indexOf('/');
            iLast = sTmpVal.lastIndexOf('/');

			//check to see if a slash exists
            if (iFirst < 0) {
				window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
				vObj.focus();
				return false;
            }
			else {
				//check to make sure there
				//are two slashes
				if (iFirst == iLast) {
				    window.alert('There is only one slash or dash in ' + vDispName + '. Please enter a date in the following format: MM/DD/YYYY');
				    vObj.focus();
				    return false;
				}

			}

			//if we are here, then there are two
			//slashes, so go ahead and get the
			//month, day, and year values
			sMonth = sTmpVal.substring(0, iFirst);
			sDay = sTmpVal.substring(iFirst + 1, iLast);
			sYear = sTmpVal.substring(iLast + 1, sValue.length);

		    //validate the year 
			//make sure there are 4 digits for the year
			if (sYear.length != 4) {
				window.alert('Please enter a 4 digit year in ' + vDispName + '.');
				vObj.focus();
				return false;
			}
			else {
				var lYear = 0;
				lYear = parseInt(sYear);

				//check for chars instead
				//of digits, if any
				if (lYear != sYear) {
					window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
					vObj.focus();
					return false;
				}

				//make sure we are at least year 1900
				if (lYear < 1900) {
					window.alert('Please enter a valid year (at least 1900) for the date in ' + vDispName + '.');
					vObj.focus();
					return false;
				}
			}

			//validate the month
			//make sure there is either 1 or two digits for the month
			if ((sMonth.length < 1) || (sMonth.length > 2)) {
				window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
				vObj.focus();
				return false;
			}
			else {
				//convert the month to a number
				//and check if it is valid
				var lMonth = 0;
				
				//this is crap!!!!!!				
				//this code is for the parseInt bug, which returns
				//a 0 if the value is 08 or 09...remove if this is fixed later
				if (sMonth.charAt(0) == '0' && sMonth.charAt(1) == '8') {
					sMonth = '8';
				}

				if (sMonth.charAt(0) == '0' && sMonth.charAt(1) == '9') {
					sMonth = '9';
				}

				lMonth = parseInt(sMonth);

				//see if there were any
				//chars entered instead of digits
				if (lMonth != sMonth) {
					window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
					vObj.focus();
					return false;
				}

				//now check to make sure the month 
				//is between 1 and 12
				if ((lMonth < 1) || (lMonth > 12)) {
					window.alert('Please enter a valid month for the date in ' + vDispName + '.');
					vObj.focus();
					return false;
				}

				//get the maximum
				//days for the month
				switch (lMonth) {
					case 1:
						lDayMax = 31;
						break;
					case 2:
						lDayMax = (sYear % 4 == 0 && (sYear % 100 != 0 || sYear % 400 == 0)) ? 29 : 28;
						break;
					case 3:
					case 5:
					case 7:
					case 8:
					case 10:
					case 12:
						lDayMax = 31;
						break;
					default:			
						lDayMax = 30;
						break;
				}
			}

		    //validate the day 
			//make sure there is either 1 or 2 digits for the day
			if ((sDay.length < 1) || (sDay.length > 2)) {
				window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
				vObj.focus();
				return false;
			}
			else {
				//convert the day to a number
				//and check if it is valid

				//this is crap!!!!!!				
				//this code is for the parseInt bug, which returns
				//a 0 if the value is 08 or 09...remove if this is fixed later
				if (sDay.charAt(0) == '0' && sDay.charAt(1) == '8') {
					sDay = '8';
				}

				if (sDay.charAt(0) == '0' && sDay.charAt(1) == '9') {
					sDay = '9';
				}

				var lDay = 0;
				lDay = parseInt(sDay);

				//see if there were any
				//chars entered instead of digits
				if (lDay != sDay) {
					window.alert('Please enter a date in ' + vDispName + ' in the following format: MM/DD/YYYY');
					vObj.focus();
					return false;
				}

				//now check to make sure the day 
				//is between 1 and the end of the month
				if ((lDay < 1) || (lDay > lDayMax)) {
					window.alert('Please enter a valid day for the date in ' + vDispName + '.');
					vObj.focus();
					return false;
				}
			}

			//now check to see if this is within
			//the valid date range if any was given
			if (validDateRange(sValue, vMin, vMax) == false) {
				window.alert('Please enter a date between ' + vMin + ' and ' + vMax + ' in ' + vDispName + '.');
				vObj.focus();
				return false;
			}

			break;

		default:

			//alert('default');			
			return false;
			break;
	}

    return true;
}
function isnumeric(ch) {
	return (ch>='0' && ch<='9');
}


/*------------------------------------------------
function:
	validateDateRange

Description:
	Use this function when you want to make sure that 
	the date in question is either before and/or after a 
	min or max date value.
	
	Also validates that the date in question is a valid
	date.
	
Arguments:
	obj				- the object that contains the date we are validating.
	minDate			- the minimum allowable date value that the date object.
	maxDate			- the maximum allowable date value of the date object.
	displayName		- the display name of the date object for the alert message
	minDisplayName	- the display name of the minimum date value. If blank
					  the message will display the minDate value.
	maxDisplayName	- the display name of the maximum date value. If blank
					  the message will display the maxDate value.
	allowNulls		- boolean indicating whether this date object can be empty string.

Returns:
	boolean indicating whether the date object passed all validation,
	and sets focus to the date object on a negative return.
 ------------------------------------------------*/
function validateDateRange(startObj, endObj, startDispName, endDispName, startAllowNulls, endAllowNulls)
{
	var dispName = '';
	var bstartAllowNulls = (startAllowNulls==false ? false : true); //use true as default
	var bendAllowNulls = (endAllowNulls==false ? false : true);     //use true as default
	
	//Error if start doesn't allow nulls but field is blank
	if ((!bstartAllowNulls) && (startObj.value.length == 0)) {
		alert('Please enter a value in ' + startDispName + '.');
		return false;
	}

	//Error if end doesn't allow nulls but field is blank
	if ((!bendAllowNulls) && (endObj.value.length == 0)) {
		alert('Please enter a value in ' + endDispName + '.');
		return false;
	}

	//Exit if both are blank and blanks are allowed
	if (((bstartAllowNulls) && (startObj.value.length == 0)) &&
	    ((bendAllowNulls) && (endObj.value.length == 0))) {
		return true;
	}

	// Check to see the start date is valid
	if (!validateDate(startObj, startDispName, startAllowNulls)) {
		startObj.focus();
		return false;
	}
	// Check to see the end date is valid
	if (!validateDate(endObj, endDispName, endAllowNulls)) 
	{
		endObj.focus();
		return false;
	}
	if (!validDateRange(endObj.value, startObj.value, '')) 
	{
		alert('The ' + endDispName + " date cannot be before the " +  startDispName + " date.");
		endObj.focus();
		return false;
	}    
	return true;	
}

function textCounter(field, maxlimit) {
	if (field.value.length > maxlimit) { 
		// trim the value if it exceeds the limit.
		field.value = field.value.substring(0, maxlimit);
	}
}


//function modify by hemant kumar for the given datetime format.
function validateDate(vObj, vDispName, allowNulls) {
	
	var DayPosition;
	var MonthPosition;
	var YearPosition;
	var sdateformat
	
	DayPosition = dateFormat.indexOf("d",0);
	MonthPosition = dateFormat.indexOf("m",0);
	YearPosition = dateFormat.indexOf("y",0);
	var arr=new Array();	
	arr= vObj.value.split("/");

	var sValue = vObj.value;
    var sTmpVal = sValue;
    var iFirst = 0;
    var iLast = 0;
    var sDay = '0';
    var sMonth = '0';
    var sYear = '0';
	var lDayMax = 0;
	var lMonth = 0;
	var lDay = 0;
	
    sDay = arr[DayPosition];
	sMonth = arr[MonthPosition];
	sYear = arr[YearPosition];

	var dateexpr_mdy = /^(0|1)?\d{1}[\/](0|1|2|3)?\d{1}[\/]\d{4}$/
	var dateexpr_dmy = /^(0|1|2|3)?\d{1}[\/](0|1)?\d{1}[\/]\d{4}$/
	//var dateexpr_ymd = /^(d{4})[\/](0|1)?\d{1}[\/](0|1|2|3)?\d{1}$/
	//var dateexpr_ymd = /^(19|20)\d\d[\/](0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])$/
	var dateexpr_ymd = /^(19|20)\d\d[\/](0|1)?\d{1}[\/](0|1|2|3)?\d{1}$/
	var bRetVal = false;
	
	if ((allowNulls) && (sValue.length == 0)) {
		return true;
	}
	
	if(dateFormat=="dmy")
	{
	    bRetVal =  dateexpr_dmy.test(sValue);
	    sdateformat="DD/MM/YYYY";
	}
	if(dateFormat=="mdy")
	{
	    bRetVal =  dateexpr_mdy.test(sValue);
	    sdateformat="MM/DD/YYYY";
	}
	if(dateFormat=="ymd")
	{
	    bRetVal =  dateexpr_ymd.test(sValue);
	    sdateformat="YYYY/DD/MM";
	    //alert("here");
	}
	

	if (bRetVal == false) {
		alert ('Please enter a date in ' + vDispName + ' in the following format :' + sdateformat);
		vObj.focus();
		return false;
	}


	//make sure we are at least year 1900
	if (parseInt(sYear) < 1900) {
		window.alert('Please enter a valid year (at least 1900) for the date in ' + vDispName + '.');
		vObj.focus();
		return false;
	}

	//convert the month to a number
	//and check if it is valid
	//this is crap!!!!!!				
	//this code is for the parseInt bug, which returns
	//a 0 if the value is 08 or 09...remove if this is fixed later
	if (sMonth.charAt(0) == '0' && sMonth.charAt(1) == '8') {
		sMonth = '8';
	}

	if (sMonth.charAt(0) == '0' && sMonth.charAt(1) == '9') {
		sMonth = '9';
	}

	lMonth = parseInt(sMonth);


	//now check to make sure the month 
	//is between 1 and 12
	if ((lMonth < 1) || (lMonth > 12)) {
		window.alert('Please enter a valid month for the date in ' + vDispName + '.');
		vObj.focus();
		return false;
	}

	//get the maximum
	//days for the month
	switch (lMonth) {
		case 1:
			lDayMax = 31;
			break;
		case 2:
			lDayMax = (sYear % 4 == 0 && (sYear % 100 != 0 || sYear % 400 == 0)) ? 29 : 28;
			break;
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			lDayMax = 31;
			break;
		default:			
			lDayMax = 30;
			break;
	}


	//this is crap!!!!!!				
	//this code is for the parseInt bug, which returns
	//a 0 if the value is 08 or 09...remove if this is fixed later
	if (sDay.charAt(0) == '0' && sDay.charAt(1) == '8') {
		sDay = '8';
	}

	if (sDay.charAt(0) == '0' && sDay.charAt(1) == '9') {
		sDay = '9';
	}

	lDay = parseInt(sDay);

	//now check to make sure the day 
	//is between 1 and the end of the month
	if ((lDay < 1) || (lDay > lDayMax)) {
		window.alert('Please enter a valid day for the date in ' + vDispName + '.');
		vObj.focus();
		return false;
	}

	return true;
}

function validateMoney(vObj, vDispName, vAllowNulls) {
	var sValue = vObj.value;
	sValue = Trim(sValue);
	vObj.value = sValue;
	
	//first check the allow nulls
    if (sValue.length == 0) {
        if (vAllowNulls == false) {
             alert('Please enter a value in ' + vDispName + '.');
             vObj.focus();
             return false;
        }
		return true;
    }

	var charsAllowed = ' -,.0123456789';
	var numcharsAllowed = '-.0123456789';
	var decCnt = 0;
	var necCnt = 0;
	var val = "";
	var i;
	
    // Search through string's characters one by one.
    // If character is in charsAllowed, append to val.

    for (i = 0; i < sValue.length; i++) {   
        // Check that current character isn't whitespace.
        var c = sValue.charAt(i);
        if (c == '.') { decCnt += 1; }
        
        //only first character can be a minus sign
        if ((i != 0) && (c == '-')) {
			alert('Invalid number in ' + vDispName + '.');
			vObj.focus();
			return false;
        }
        
        //if (charsAllowed.indexOf(c) != -1) val += c;
        if (charsAllowed.indexOf(c) == -1) {
			alert('Invalid character(s) were entered in ' + vDispName + '. The following characters are valid: ,.0123456789.');
            vObj.focus();
            return false;
        }
        else if (decCnt > 1) {
			alert('Invalid number in ' + vDispName + '.  Only one decimal point is allowed.');
			vObj.focus();
			return false;
        }
        else if (numcharsAllowed.indexOf(c) != -1) {val += c;}
    }
	
	val = parseFloat(val);

	// Check that the value is not bigger than the biggest money value that SQL can hold.
	if (val > 922337203685477.00) {
		alert('Invalid number in ' + vDispName + '. Number cannot be greater than 922,337,203,685,477.00.');
		vObj.focus();
		return false;
	}

	//convert to positive number if it is negative
	var negNum = false;
	if (val < 0) { 
		negNum = true; 
		val = val * -1;
	}
	
	//add decimal values
	val = Math.round(val*100)/100;
	val = (val == Math.floor(val)) ? val + '.00' : ((val*10 == Math.floor(val*10)) ? val + '0' : val);

	//insert comma if necessary	
	var sval = val.toString(); 
	var i = sval.indexOf('.');
	var delimeter = ",";
	while (i>3) {
		sval = sval.substring(0,i-3)+delimeter+sval.substring(i-3);
		i = i-3;
	}
		
	//convert back to negative if necessary
	if (negNum == true) {
		sval = '-' + sval;
	}	
		
	vObj.value = sval;
	return true;
	//vObj.focus();
}

function strToFloat(amount) {
	var charsAllowed = '-.0123456789';
	var val = "";

    // Search through string's characters one by one.
    // If character is in charsAllowed, append to val.

    for (i = 0; i < amount.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = amount.charAt(i);
        if (charsAllowed.indexOf(c) != -1)  val += c;
    }
   
    return val;
}