// Returns a value equal to numStr with newDecPlaces decimals at most.  Adds trailing zeros if flag is set to true
function setDecPlaces(numStr, newDecPlaces, addTrailingZerosFlag) {

  numStr = numStr.toString(); // make sure numStr is a string
  var decIndex = numStr.indexOf('.');
  var decPlaces = 0;
  if (decIndex != -1) {
    decPlaces = numStr.length - decIndex - 1;
  }
  
  if (newDecPlaces == 0 && decIndex != -1) {
    numStr = numStr.substring(0, decIndex); // strip decimal point
  } else if (decPlaces > newDecPlaces) {
    numStr = numStr.substring(0, (decIndex + newDecPlaces + 1)); // remove decimal places
  } else if (decPlaces < newDecPlaces && addTrailingZerosFlag) { // add trailing zeros if necessary
    if (decIndex == -1) {
      numStr = numStr + "."; // add a decimal point if there isn't one
    }
    for (; decPlaces < newDecPlaces; decPlaces++) { // add enough zeros such that decPlaces = newDecPlaces
      numStr = numStr + "0";
    }
  }

  return NaNToZero(numStr);
}

// Returns a string value of "0" if the argument is not a number or empty
function NaNToZero(value) {
  if (value == null || value == "" || isNaN(value)) {
    return "0";
  } else {
    return value;
  }
}

function fillZeros(theForm) {
  var e;
  for (var i = 0; i < theForm.elements.length - 1; i++) {
    e = theForm.elements[i];
    // modify hidden or text fields that are empty
    if ((e.value == null || e.value == "") &&
        (e.type == "text" || e.type == "hidden")) {
      theForm.elements[i].value = 0;
    }
  }
}

// Use this test string (which should clean up to 123.45678901):  1c,><2;:'"[]3\|=+-_)(*&^%$$#@!~`.sd 45678901
function cleanUpField(field) {
  stripIllegalChars(field);
  switch (field.name) { // strip decimals
    // no decimals
    case "txtTerm":  
      field.value = setDecPlaces(field.value.toString(), 0);
      break;
    // 2 dec places
    case "txtAmount": case "txtDown":
      field.value = setDecPlaces(field.value.toString(), 2);
      break;
    // 3 dec places
    case "txtRate": 
      field.value = setDecPlaces(field.value.toString(), 3);
      break;
  }
}

function stripIllegalChars(field) {
//  alert(field.value + " " + field.name);
  var regExp = /[^0123456789.]+/;
  var val = field.value;
  while (val.match(regExp)) val = val.replace(regExp, ""); // remove all non-numbers (keep decimals)
  val = NaNToZero(val); // set blank fields to zero
  field.value = val;
}

/*
  Checks _field_ for errors. The type of error check is determined by _name_. x, y & z hold other necessary values
*/
function checkError (field) {
  var errorFlag = false;
  switch (field.id) {

    case "txtPrice": // Vehicle Price
      var vp = parseFloat(field.value);
      var dp = parseFloat(document.getElementById("txtDown"));
      if ( (vp < dp ) || (vp > 500000) ) {
        errorFlag = true;
        alert("Vehicle Price must be greater than Down Payment and less than $500,000.");
      }
    break;

    case "txtDown": // Down Payment
      var dp = parseFloat(field.value);
      var vp = parseFloat(document.getElementById("txtPrice"));
      if (vp < dp) {
        errorFlag = true;
        alert("Down Payment must be less than Vehicle Price.");
      }
    
    break;

    case "txtTax": // Sales Tax
      if (parseFloat(field.value) < 0 || parseFloat(field.value) > 100) {
        errorFlag = true;
        alert("Sales Tax must be between 0 and 100.");
      }
    break;
      
    case "txtRate":
      if (parseFloat(field.value) < 0 || parseFloat(field.value) > 50) {
        errorFlag = true;
        alert("Interest Rate must be between 0 and 50.");
      }
    break;

    case "txtTerm":
      if (parseFloat(field.value) < 6 || parseFloat(field.value) > 72) {
        errorFlag = true;
        alert("Term of loan must be between 6 and 72." );
      }
    break;
  }
  
  if (errorFlag) {
    var calcForm;
    field.select();
    field.focus();
    return true;
  } 
  else {
    return false;
  }
}


// Used for field validation.
var dirtyField = true
var validating = false


//=================================================
function validRange(field)
{
  var fieldMin = 0
  var fieldMax = 500000
  
  if (parseFloat(field.value) < parseFloat(fieldMin) || parseFloat(field.value) > parseFloat(fieldMax))
  {
    return false
  }
  else
  {
    return true
  }
}

function validateField(field)
{
   
   cleanUpField(field);
   var numErrFlag = false
   var rangeErrFlag = false
   
   if (field.value == "") field.value = 0;
   
   if (!isNumeric(field.value))
   {
      alert('Must be numeric.')
      field.value = ''
      field.select()
      field.focus()
      return
   }
   else
   {
      if(!validRange(field))
      {
         alert('Field not in range of acceptible values.')
         field.value = ''
         field.select()
         field.focus()
         return;
      }
   }
   checkError(field);
}

//=================================================
function changedField()
{
   dirtyField = "true"
}


//=================================================
function isNumeric(strString) {
	
	var strValidChars = "0123456789.";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		//alert(strChar);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
	
}
