// Reformat Fields Common JavaScript
//
// Common function for formatting fields upon user entry.  will handle
// validation and formatting of numeric and currency fields.
//
// Author:  Brian Bailey (The Seva Group)
// Date:    September 29, 1999
//
// Revisions:
//
//		Author			Date		Description of Changes
//		===================================================
//		B.Bailey		09/29/1999	Original creation.
//      B.Bailey        04/16/2000  Changed math.floor to math.round in getdatediff
//

// creates new object for number validation.  called only within routine.
function CreateNumericUnit() {
	this.InputValue = " ";
	this.OutputValue = " ";
	this.CurrencySymbol = " ";
	this.strErrorMsg = " ";
}

// Validates each digit and removes extraneous characters.  called only within routine.
function CheckNumeric(objNumericUnit) {

	(objNumericUnit.OutputValue) = "";
	var blnNegative = false;
		
	for (var i=0; i < objNumericUnit.InputValue.length; i++) {

		var digit = objNumericUnit.InputValue.charAt(i)
		var chkidx = i

		if (parseFloat(digit) || digit == "." || digit == "0") {
			(objNumericUnit.OutputValue) += digit
		}
		else {
			if (digit != " " && digit != objNumericUnit.CurrencySymbol && digit != "," && digit != "-") {
				objNumericUnit.strErrorMsg = "Invalid character found in numeric field: " + digit
				return false
			}
			if (digit == "-") {
				if (!blnNegative) {
					(objNumericUnit.OutputValue) += digit
					blnNegative = true
				}
				else {
					objNumericUnit.strErrorMsg = "Multiple negative signs encountered in number"
					return false
				}
			}
		}
	}
	return true;	
}	

// main function that will be called by calling programs.
// Input parameters:  objInputField - the name of the field that is having validation performed.  Is 
//								      treated as an object, so don't put a ".value" on the end of it
//                                    when calling.
//					  blnIncludeCommas - 0 is No, 1 is Yes.  Routine will put in commas for you if  requested.
//                    blnOverrideDecimals - 0 is No, 1 is Yes. Will either use the numDigitsAfterDecimal 
//											 variable or not depending on this flag.
//                    numDigitsAfterDecimal - number of places after the decimal to allow/pad.
//                    strCurrencySymbol - currency symbol that should be displayed on front of field.
function FormatNumericAndCurrency(objInputField, blnIncludeCommas, blnOverrideDecimals, numDigitsAfterDecimal, strCurrencySymbol) {

if (objInputField.value != "") {

	// Check for valid numerics and remove extraneous characters
	var objNumericUnit = new CreateNumericUnit();

	(objNumericUnit.InputValue) = objInputField.value;
	(objNumericUnit.OutputValue) = "";
	(objNumericUnit.CurrencySymbol)  = strCurrencySymbol;
	(objNumericUnit.strErrorMsg)  = "";

	if (CheckNumeric(objNumericUnit)) {
		// field passed validation okay
	}
	else {
		alert((objNumericUnit.strErrorMsg))
		return false
	}

	// check for negative value and strip off for future addition.
	if (objNumericUnit.OutputValue.substring(0, 1) == '-') {
		// strip off negative sign and set flag
		blnNegativeValue = true
		tmpValue = objNumericUnit.OutputValue
		objNumericUnit.OutputValue = tmpValue.substring(1, tmpValue.length)
	}
	else {
		blnNegativeValue = false
	}
	
	// Check for decimal place existence.
	idxFirstDecimal = objNumericUnit.OutputValue.indexOf('.');
	idxLastDecimal  = objNumericUnit.OutputValue.lastIndexOf('.');
	
	if (idxFirstDecimal >= 0) { // At least one decimal point found.

		if (idxLastDecimal != idxFirstDecimal) { // too many decimals error
			alert("Only one decimal point should be entered")
			return false
		}

		numArray = objNumericUnit.OutputValue.split('.')
		numLeftOfDecimal = numArray[0]
		numRightOfDecimal = numArray[1]
		if (numLeftOfDecimal == "") {numLeftOfDecimal = "0"}

	}
	else { // no decimals are present in input number.  
		numLeftOfDecimal = objNumericUnit.OutputValue
		numRightOfDecimal = ""
	}	

	if (blnOverrideDecimals) {
		// Pad right of decimal with trailing zeroes as appropriate
		for (var digit = numRightOfDecimal.length; digit < numDigitsAfterDecimal; digit++) {
			numRightOfDecimal += "0"
		}

		if (numRightOfDecimal.length > 0) { // chop off digits if they entered more than allowed.
			numRightOfDecimal = numRightOfDecimal.substring(0, numDigitsAfterDecimal)	
		}
	}	

	if (blnIncludeCommas) {
	
		switch(numLeftOfDecimal.length) {
			case 1:
				break;
			case 2:
				break;
			case 3:
				break;
			case 4:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 1) + 
									"," + 
									numLeftOfDecimal.substring(1,4)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 5:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 2) + 
									"," + 
									numLeftOfDecimal.substring(2,5)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 6:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 3) + 
									"," + 
									numLeftOfDecimal.substring(3,6)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 7:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 1) + 
									"," + 
									numLeftOfDecimal.substring(1,4) + 
									"," + 
									numLeftOfDecimal.substring(4,7)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 8:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 2) + 
									"," + 
									numLeftOfDecimal.substring(2,5) + 
									"," + 
									numLeftOfDecimal.substring(5,8)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 9:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 3) + 
									"," + 
									numLeftOfDecimal.substring(3,6) + 
									"," + 
									numLeftOfDecimal.substring(6,9)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 10:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 1) + 
									"," + 
									numLeftOfDecimal.substring(1,4) + 
									"," + 
									numLeftOfDecimal.substring(4,7) +
									"," +
									numLeftOfDecimal.substring(7,10)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 11:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 2) + 
									"," + 
									numLeftOfDecimal.substring(2,5) + 
									"," + 
									numLeftOfDecimal.substring(5,8) +
									"," +
									numLeftOfDecimal.substring(8,11)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 12:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 3) + 
									"," + 
									numLeftOfDecimal.substring(3,6) + 
									"," + 
									numLeftOfDecimal.substring(6,9) +
									"," +
									numLeftOfDecimal.substring(9,12)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			default:
				alert("A number of length greater than 12 left of the decimal was passed to comma insert routine.  Can only handle up to 12 places")
				return false
				break;
		}
	}

	if (strCurrencySymbol != "") { // create output field with currency symbol on front.
		numLeftOfDecimal = strCurrencySymbol + numLeftOfDecimal
	}

	if (blnNegativeValue) {
		numLeftOfDecimal = "-" + numLeftOfDecimal
	}	
	
	if (numRightOfDecimal.length != 0) {
		objInputField.value = numLeftOfDecimal + "." + numRightOfDecimal
	}
	else { // don't include the decimal point.
		objInputField.value = numLeftOfDecimal
	}
}	
	return true;	

}

// Date validation routine.  will take either 2 or 4 digit years.  Will default to current year if no year is provided.
function Valid_Date(objInputDate){
        
        var dtInput=objInputDate.value;

        if (dtInput.indexOf("-")!=-1){
                var sdate = dtInput.split("-")
				var strDelim = "-"
        }
        else {
                var sdate = dtInput.split("/")
				var strDelim = "/"
        }
		
        if (sdate.length != 3 && sdate.length != 2) {
            alert("Incorrect number of components found in date.  Format should be MM/DD/YY or MM/DD/YYYY or MM/DD")
            return false
        }

		if (sdate.length == 2) { //format used was mm/dd.  year must be set to current year
			var currdate = new Date()
			sdate.length += 1
			sdate[2] = currdate.getFullYear()
			dtInput = dtInput + strDelim + sdate[2]
		}
		else {		
    	    // Make sure that we have a 4 digit year.  If not, add the century to the front.

	        if (sdate[2].length == 4) {
        	    // no action.  this is expected.
    	    }
	        else if (sdate[2].length == 2) { // tack century onto front.

            	if (sdate[2] > 83) {sdate[2] = "19" + sdate[2]}
        	    else {
					tempdate = "20" + sdate[2]
					sdate[2] = tempdate
					dtInput = sdate[0] + strDelim + sdate[1] + strDelim + sdate[2]
				}
    	    }
	        else {
        	    alert("Invalid length of year.  Enter either a 2 or 4 digit year")
    	        return false
	        }
        }
		
        var chkDate=new Date(Date.parse(dtInput))
        var cmpDate=(chkDate.getMonth()+1)+"/"+(chkDate.getDate())+"/"+(chkDate.getFullYear())
        var indate2=(Math.abs(sdate[0]))+"/"+(Math.abs(sdate[1]))+"/"+(Math.abs(sdate[2]))

        if (indate2!=cmpDate){
                alert("You've entered an invalid date or date format.  Please use the MM/DD/YY or MM/DD/YYYY format.")
                return false
        }
        else {
                if (cmpDate=="NaN/NaN/NaN"){
                        alert("You've entered an invalid date or date format.  Please use the MM/DD/YY or MM/DD/YYYY format.");
                        return false
                }
                else {
                        objInputDate.value = cmpDate
                        return true
                }       
        }
}

// Return the difference (in days) between two dates.  Value can be negative if the first date
// provided is after the second date.
function GetDateDiff(dtFirst, dtSecond) {
	tempfirst = Date.parse(dtFirst)
	tempsecond = Date.parse(dtSecond)
	numDaysDiff = tempsecond - tempfirst
	numDaysDiff = Math.round(numDaysDiff / (1000 * 60 * 60 * 24));
	return numDaysDiff;
}

function ValidateIndividualDate(objDateField) {

	if (objDateField.value != "") {
		if (Valid_Date(objDateField)) {
			return true
		}
		else {
			objDateField.focus()
			return false
		}
	}
	return true;
}

// Added 1/4/2000 - bjb
function ValidateBetweenDates(objDateLow, objDateHigh) {

	if (objDateLow.value != "" && objDateHigh.value == "") {
		alert("You must also enter a high end date if you enter a low end date")
		objDateHigh.focus()
		return false
	}
	
	if (objDateHigh.value != "" && objDateLow.value == "") {
		alert("You must also enter a low end date if you enter a high end date")
		objDateLow.focus()
		return false
	}
	
	if (objDateLow.value != "" && objDateHigh.value != "") {	
	
		if (ValidateIndividualDate(objDateLow)) {// no action
		}
		else {return false}

		if (ValidateIndividualDate(objDateHigh)) {// no action
		}
		else {return false}
	
		// Make sure that high date is beyond the low date
		if (GetDateDiff(objDateLow.value, objDateHigh.value) < 0) {
			alert("The high end date must be greater than or equal to the low end date in a date search")
			objDateLow.focus()
			return false
		}
	}
	return true;
}

// Verify Percentage Entry

// modified to add closing brackets and change equality checks to assignment statements - 12/15 bjb
/*
function Value_Percentage(objInputField) {
	if (objInputField.value != "") {
		var valper = objInputField.value;
		if (valper.value >= 0 && valper.value < 1) {
			if (valper.value <= 1) {
				valper.value = valper.value  		
			}
		}
		else {
			objInputField.focus()
			return false;
		}

	}
	return true;
}
*/