// 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
// 22-Sep-06 DP - Changed ValidCurrency function to use regular expressions and handle negative amounts.
//
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 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 a minumum of " + 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 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 enter a value 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.getFullYear();
	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 ValidCCExp


function ValidCurrency(theField) {

	if (theField.value=="") { return true; }
	var val = theField.value;
	var amtExpr = /^[\-\(]?\$?\d{1,3}(\,?\d{3}){0,}(\.\d{0,2})?\)?$/;
	ret = false;

	ret = amtExpr.test(val);
	if (!ret) {
		alert("Invalid currency format for '" + val + "' !");
		return false;
	}
	else {
		return true;
	}
 }  // end of ValidCurrency


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