function chkVin(textBox) {
  var s = textBox.value;

  if (s.length != 17) {
    textBox.className = "vin-error";
    return true;
  }

  if (checkDigitCalc(s) != s.charAt(8)) {
    textBox.className = "vin-error";
    return true;
  }

  textBox.className = "vin-clean";
  return true;
}

function checkDigitCalc(vin) {
  var vinChars = "ABCDEFGHJKLMNPRSTUVWXYZ1234567890";
  var vinValues = new Array (1,2,3,4,5,6,7,8,1,2,3,4,5,7,9,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,0);
  var vinWeights = new Array (8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2);

  var badvin = "error";

  if (vin.length != 17)
    return badvin;  // if VIN length is invalid then abort

  // Lower case breaks the check digit!
  vin = vin.toUpperCase();

  var vinProblem = false;
  var sum = 0;

  for (i=0; i < 17; ++i) {
    valid = vinChars.indexOf(vin.charAt(i));
    if (valid < 0) {
      // if invalid character found in VIN then abort
      vinProblem = true;
      break;
    }

    // multiply value of VIN character times weight of its position in VIN
    // add them all up
    sum += (vinValues[valid] * vinWeights[i]);
  }

  if (vinProblem == true)
    return badvin;

  // divide the total by 11 and use the remainder
  remainder = sum % 11;

  // if the remainder is 10, the check digit is X
  if (remainder == 10)
    return 'X';
  else
    // otherwise the remainder becomes the check digit of 0-9:
    return remainder.toString();
}

