// javaValidation.js - validation routines for entry/edit fields
// 17-April-03 Paul - Added ValidCurrency - checks if field is valid currency
// 17-Jun-02 Rob - Added ValidCCExp To Check Expiration date of credit card
// 26-Feb-03 DP - Fixed ValidateRadioFields to check for more than 2 buttons
// 26-Oct-03 Rob - Added ValidURL for validating URL fields
// 26-Oct-03 Rob - Added validateContents for advanced field validation
// 26-Oct-03 Rob - Added validateImage for image validation
// 8-Dec-03 Rob - Added checkMinLen for validating a minimum number of characters
// 14-May-04 Rob - Added validateTextFile for text file validation
//
function ValidNum(theField, name) {
	// Validate a numeric field.
	// theField	- the field to validate
	// name		- the displayed name for this field
	if (theField.value=="") { return true; }
	if (isNaN(theField.value)) {
		alert("Please enter a number for the \"" + name + "\" field. Please do not use any commas or decimals when entering the number.");
		theField.focus();
		return false;
	}
	return true;
}	// end of ValidNum

function getCurYear() {
	// Get current year (as 4 digit year).
	var tmpDate
	
	tmpDate=new Date();
	getCurYear=tmpDate.getYear();
	if (getCurYear<100) {
		getCurYear=getCurYear+1900;
	}	// (years between 1900 and 1999 return a 2 digit year)
}	// end of getCurYear

function ValidDate(theField, name) {
    // Validate a date in Month/Day/Year format
	if (theField.value=="") { return true; }
	var tmpMsg="Please enter a valid date for the \"" + name + "\" field.\n For example: 2/28/1999 or 5/31/01";
	var tmpLeap=28;
	var tmpDate=theField.value;
	var tmpDateParts;
	tmpDate=tmpDate + "//";		// make sure we find at least 3 date parts
	tmpDateParts=tmpDate.split("/");
	var tmpMonth = tmpDateParts[0];
	var tmpDay = tmpDateParts[1];
	var tmpYear = tmpDateParts[2];
	if (tmpYear.length==2) {tmpYear = '20' + tmpYear};	// default to current century
	// alert("Date="+tmpDate+"\n Month="+tmpMonth+"\n Day="+tmpDay+"\n Year="+tmpYear);
	if (isNaN(tmpYear) || tmpYear<1800 || tmpYear>2099 ||
			isNaN(tmpMonth) || tmpMonth<1 || tmpMonth>12 ||
			isNaN(tmpDay) || tmpDay>31 || tmpDay<1 ) {
		alert(tmpMsg);
		theField.select();
		theField.focus();
		return false;
	}
	if ((tmpYear & 3) == 0 && tmpYear != 1900 && tmpMonth==2) {tmpLeap=29};
	if (tmpDay>30 && (tmpMonth==4 || tmpMonth==6 || tmpMonth==9 || tmpMonth==11) ||
		(tmpDay>tmpLeap && tmpMonth==2)) {
		alert(tmpMsg);
		theField.select();
		theField.focus();
		return false;
	}
	return true;
}   // end of ValidDate

function ValidMinMax(theField, name, lowval, hival) {
	// Validate that user entered a value between a min and max for a field.
	// Input:
	//		theField	- the field to validate
	//		name		- the displayed name for this field
	//		lowval		- lowest valid value
	//		hival		- highest valid value
	if (theField.value=="") { return true; }
	if ((theField.value < lowval) || (theField.value > hival)) {
		alert("The \"" + name + "\" field MUST be between " + lowval + " and " + hival +".");
		theField.focus();
		return false;
	}
	return true;
}	// end of ValidMinMax

function MustEnter(theField, name) {
	// See if user has entered something in a mandatory field.
	// Input:
	//		theField	- the field to check
	//		name		- the displayed name for this field
	// alert("The \"" + name + "\" field='" + theField.value + "'");
	var tmpStr
	tmpStr=theField.value.replace(/\ /g,"");

	if (tmpStr == "") {
		alert("Please enter a value for the \"" + name + "\" field.");
		theField.value="";	// clear the field
		theField.focus();
		return false;
	}
	return true;
}	// end of mustEnter

function CheckLen(theField, name, maxLen) {
	// See if what the user entered is too long for the field.
	// Input:
	//		theField	- the field to check
	//		name		- the displayed name for this field
	//		maxLen		- maximum length for this field
	if (theField.value.length > maxLen) {
		alert("You have entered " + theField.value.length + " characters into the \"" + name + "\" field. \n This field can only take " + maxLen + " characters.");
		theField.focus();
		return false;
	}
	return true;
}	// end of CheckLen

function CheckMinLen(theField, name, minLen) {
	// See if what the user entered is not long enough for the field.
	// Input:
	//		theField	- the field to check
	//		name		- the displayed name for this field
	//		maxLen		- maximum length for this field
	if (theField.value.length < minLen) {
		alert("You must enter " + minLen + " characters into the \"" + name + "\" field.");
		theField.focus();
		return false;
	}
	return true;
}	// end of CheckMinLen

function MustEnterOne(theField1, theField2, name1, name2) {
	// See if user has entered something in either one of a pair of fields.
	// Input:
	//		theField1	- 1st field to check
	//		theField2	- 2nd field to check
	//		name1		- the displayed name for 1st field
	//		name2		- the displayed name for 2nd field
	// alert("The \"" + name1 + "\" field='" + theField1.value + "'"
	//	+ "\nThe \"" + name2 + "\" field='" + theField2.value + "'");
	if (theField1.value.length==0 && theField2.value.length==0) {
		alert('You must enter a value in either the ' + name1 + ' or the ' + name2 + ' field.');
		if (theField2.value.length==0) {
			theField2.focus();
		}
		if (theField1.value.length==0) {
			theField1.focus();
		}
		return false;
	}
	return true;
}	// end of mustEnterOne

function MustCheckOne(theField1, theField2)
{
  if   ((theField1.checked) ||
	(theField2.checked)){
        	return true;
      	}
   else
   {
   	alert("You must check at least one \"Services Needed\" check box.");
   	return false;
   }
}

function MustCheckOneTwo(theField1, theField2, theField3)
{
  if   ((theField1.checked) ||
       	(theField2.checked) ||
	    (theField3.checked)){
        	return true;
      	}
   else
   {
   	alert("You must check at least one \"Good Time to Call Me\" check box.");
   	return false;
   }
}

function ValidateRadioFields(theField, name) {
	if (theField.length==undefined) {
		if (theField.checked) {
			return true;
		}
	}
	for (var i = 0; i < theField.length; i++) {
		if (theField[i].checked) {
			return true;
		}
	}
	alert("Please select a choice for the \"" + name + "\" field.");
	return false;
} // end of ValidateRadioFields

function validateDDwText(theField, name) {
	if (theField[0].value.length==0 & theField[1].value.length==0) {
		alert("Please enter a value for the \"" + name + "\" field.");
		return false;
	}
	return true;
} // end of validateDDwText

function ValidPassword(theForm) {
	// Validate the password fields.
	// Input:
	//		theForm	- the form to validate
	//		theForm.Password.value	- value the user entered for the password field
	//		theForm.ConfirmPassword.value - value the user entered for the ConfirmPassword field

	if (theForm.Password.value=="") {
		alert("You MUST enter a value for the Password field.");
		theForm.Password.focus();
		return false;
	}
	if (theForm.Password.value != theForm.ConfirmPassword.value) {
		alert("The Password and the Confirmed Password do not match.  Please re-enter them.");
		theForm.Password.focus();
		return false;
	}
	return true;
}	// end of ValidPassword

function ValidEmail(theField) {
    // Validate an e-mail address
    if (theField.value=="") {
	    return true;
	}
	if (theField.value.indexOf("@") != "-1" &&
	    theField.value.indexOf(".") != "-1" &&
		theField.value.length>=5
		)
	    return true;
	else {
	    alert("Please enter a valid e-mail address.");
		theField.focus();
	    return false;
	}
}   // end of ValidEmail

function ValidURL(theField) {
    // Validate a URL
    if (theField.value=="") {
	    return true;
	}
	if (theField.value.indexOf(".") != "-1" &&
		theField.value.length>=5
		)
	    return true;
	else {
	    alert("Please enter a valid URL.");
		theField.focus();
	    return false;
	}
}   // end of ValidURL

function ValidCCExp(tmpCCMonth,tmpCCYear){ 
	tmpCCYear='20'+tmpCCYear
	tmpDate=new Date();
	tmpYear=tmpDate.getYear();
	tmpMonth=tmpDate.getMonth()+1;
	// Validate an e-mail address
    if (tmpCCMonth.length==0 || tmpCCYear.length==0) {
	    alert("Please enter a valid expiration date.");
		return false;
	}
	if (tmpCCMonth < tmpMonth &&
	    tmpCCYear <= tmpYear
		){
	    alert("Your card is expired.");
		return false;
	}
	else {
	    return true;
	}
}   // end of ValidEmail


function ValidCurrency(theField)

{
	var nNum = 0;			// Total numbers for currency value.
	var nDollarSign = 0;	// Total times a dollar sign occurs.
	var nDecimal = 0;		// Total times a decimal point occurs.
	var nCommas = 0;		// Total times a comma occurs.
	var txtLen;				// Length of string passed.
	var xTxt;				// Assigned object passed.
	var sDollarVal;			// Assigned dollar amount with or without commas.
	var bComma;				
	var decPos;				// Assigned value of numbers or positions after decimal point.
	var nNumCount = 0;		// Total number between commas.
	var i;					// For forloop indexing.
	var x;					// Assigned each indivual character in string.
	// Set the xTxt variable to the object passed to this function.
	// Assign the length of the string to txtLen.
	xTxt = theField.value;
	txtLen = xTxt.length
	for(i = 0; i < txtLen; i++)
	{
		// Assign charater in substring to x.
		x = xTxt.substr(i, 1);

		if(x == "$")
			nDollarSign = nDollarSign + 1; // Sum total times dollar sign occurs.
		else if(x == ".")
			nDecimal = nDecimal + 1; // Sum total times decimal point occurs.
		else if(x == ",")
			nCommas = nCommas + 1; // Sum total times comma occurs.
		else if(parseInt(x) >= 0 || parseInt(x) <= 9)
			nNum = nNum + 1; // If the character is a number sum total times a number occurs.
		else

		{

			// Error occurs if any other character value is in the string
			// othere then the valid characters.
			alert("Currency not formated correctly! \n\nYou have entered an misformatted currency value!\nPlease enter only: Dollar" +
				  " Signs, Commas, Decimal Points, and numbers between 0...9!");
			return false;
		} // end else
	} // end for

	if(nDollarSign > 1)
	{
		alert("ERROR! \n\nYou have entered more then one dollar sign!\nPlease only enter one!");
		return false;
	} // end if

	if(nDecimal > 1)
	{
		alert("ERROR! \n\nYou have entered more then one decimal point!\nPlease only enter one!");
		return false;
	} // end if

		
	if(nDollarSign == 1)
	{
		// Make sure dollar sign in the first character in string
		// if there is a dollar sign present.
		if(xTxt.indexOf("$") != 0)
		{
			alert("ERROR!  \n\nThe dollar sign you entered is not in the correct position!");
			return false;
		} // end if
	}// end if
	
	if(nDecimal == 1)
	{
		// Get the number of numbers after the decimal point in
		// the string if there is a decimal point present
		decPos = (txtLen - 1) - xTxt.indexOf(".");
		// Floating point cannot be more then two.
		// Valid format after decimal point.
		/**********************************/
		/*   $#.##, $#.#, $.#, $#., $.##  */
		/**********************************/
		if(decPos > 2)
		{
			alert("ERROR! \n\nThe decimal point you entered is not in the correct position!");
			return false;
		} // end if
	} // end if
	if(nCommas == 0)
	{
		// If no commas are present value is a valid US
		// currency.
		return true;
	}
	else
	{
		// Get total number of dollar number(s), removing
		// floating point numbers or cents.
		nNum = nNum - decPos;
		
		// Determine if dollar sign is in string so to be 
		// removed.
		// After determining dollar sign, assign sDollarVal
		// numbers and comma(s)

		if(xTxt.indexOf("$", 0) == 0)
			sDollarVal = xTxt.substr(1, (nNum + nCommas));
		else
			sDollarVal = xTxt.substr(0, (nNum + nCommas));

		// Determine if a zero is the first number or if a
		// comma is the first or last character in the string.
		if(sDollarVal.lastIndexOf("0", 0) == 0 )
		{
			alert("ERROR! \n\nYou cannot start the dollar amount out with a zero!");
			return false;
		}
		else if(sDollarVal.lastIndexOf(",", 0) == 0)
		{
			alert("ERROR! \n\nYou cannot start the dollar amount out with a comma!");
			return false;
		}
		else if(sDollarVal.indexOf(",", (sDollarVal.length - 1)) == (sDollarVal.length - 1))
		{
			alert("ERROR! \n\nYou cannot end the dollar amount with a comma!");
			return false;
		}
		else
		{
			// Initialize bComma indicating a comma has not been
			// occured yet.
			bComma = false;
			for(i = 0; i < sDollarVal.length; i++)
			{
				// Assign charater in substring to x.
				x = sDollarVal.substr(i, 1);	
				if(parseInt(x) >= 0 || parseInt(x) <= 9)
				{
					// If x is a number add one to the number counter.
					nNumCount = nNumCount + 1;
					// Sense comma(s) are present number counter cannot
					// be more then three before the first or next comma.
					if(nNumCount > 3)
					{
						alert("ERROR! \n\nYou have a mis-placed comma!");
						return false;
					} // end if
				}
				else
				{
					// If the number counter is less then three and
					// the comma indicator is true the comma is either
					// mis-placed or there are not enough values.
					if(nNumCount != 3 && bComma)
					{
						alert("ERROR! \n\nYou have a mis-placed comma!");
						return false;
					} // end if
					// Reset the number counter back to zero.
					nNumCount = 0;
					// Set the comma indicator to true indicating
					// that the first comma has been found and that
					// there now MUST be three numbers after each
					// comma until the loop hits the end.
					bComma = true;
				} // end if
			} // end for
			// Determine if after the loop ended that there
			// was a total of three final numbers after the
			// last comma.
			if(nNumCount != 3 && bComma)
			{
				alert("ERROR! \n\nYou have a mis-placed comma!");
				return false;
			} // end if
		} // end if
	} // end if

	// Return true indicating that the value is a valid
	// currency.
	return true;
}
function stripChars(argString, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < argString.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = argString.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

function validateContents(theField, name, allowedChars, allowAlpha, allowNums) {
	var digits = "0123456789";
	var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
	var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	//First strip out any allowed characters
	var newStr=stripChars(theField.value,allowedChars)
	//Then strip out letters if allowed
	if (allowAlpha==true) {
		newStr=stripChars(newStr,lowercaseLetters);
		newStr=stripChars(newStr,uppercaseLetters)
		}
	//Then strip out numbers if allowed
	if (allowNums==true) {
		newStr=stripChars(newStr,digits)
		}
	//now check for a length
	var tmpStr
	tmpStr=newStr

	if (tmpStr == "") {
		return true;
	}
	alert("The field \"" + name + "\" contains invalid characters.");
	theField.value="";	// clear the field
	theField.focus();
	return false;
	
} // end of validateContents

function validateImage(theField, name) {
	var sCont = theField;
    var sContVal = theField.value;
    
    if (sContVal.length != 0)
    {     
        var res="no";
        
        var gfile=sContVal.toLowerCase();
        var str= new String();
        str= gfile;
        
        var finddot=str.lastIndexOf('.',str.length);
        var contain=new String();
        var contain=str.substring(finddot+1,str.length);
        
        var findslash=str.lastIndexOf('\\',str.length); // checks the occurance of '.' in photoname [creates problem in uplaoding]
        var contain2=new String();
        var contain2=str.substring(findslash+1,finddot);
        
        var sSpace = sContVal.indexOf(' ')
        var str=new String();
        str=contain2;
        var span=new RegExp("[#]","g");
        var rep=str.replace(span,"~");
        
        
        var spans1=new RegExp("[.]","g");
        var rep=rep.replace(spans1,"~");
           
                    
        var chkindex = rep.indexOf('~')
                            
        var arr=new Array('jpg','gif','tif', 'bmp'); //add file extensions here
        
        for(i=0;i<=arr.length-1;i++)
        {
            if(arr[i]==contain)
            var res="yes";
        }
            
        
        if(res != "yes" || (sContVal=="") || (chkindex != -1) )
        {
            alert("The field '" + name + "' accepts only file extensions of '.jpg, .gif, .tif, .bmp.'");
            sCont.focus();
            sCont.select();
            return false;
        }        
    }
	return true;
} // end of validateImage

function validateTextFile(theField, name) {
	var sCont = theField;
    var sContVal = theField.value;
    
    if (sContVal.length != 0)
    {     
        var res="no";
        
        var gfile=sContVal.toLowerCase();
        var str= new String();
        str= gfile;
        
        var finddot=str.lastIndexOf('.',str.length);
        var contain=new String();
        var contain=str.substring(finddot+1,str.length);
        
        var findslash=str.lastIndexOf('\\',str.length); // checks the occurance of '.' in filename [creates problem in uploading]
        var contain2=new String();
        var contain2=str.substring(findslash+1,finddot);
        
        var sSpace = sContVal.indexOf(' ')
        var str=new String();
        str=contain2;
        var span=new RegExp("[#]","g");
        var rep=str.replace(span,"~");
        
        
        var spans1=new RegExp("[.]","g");
        var rep=rep.replace(spans1,"~");
           
                    
        var chkindex = rep.indexOf('~')
                            
        var arr=new Array('csv','txt'); //add file extensions here
        
        for(i=0;i<=arr.length-1;i++)
        {
            if(arr[i]==contain)
            var res="yes";
        }
            
        
        if(res != "yes" || (sContVal=="") || (chkindex != -1) )
        {
            alert("The field '" + name + "' accepts only file extensions of '.csv, .txt'");
            sCont.focus();
            sCont.select();
            return false;
        }        
    }
	return true;
} // end of validateTextFile
