//version 11
function isbnPrefix(bc){
    bc = bc.replace(/[^0-9]+/g,'');
    prefix = bc.substr(0,3)
    return prefix == "978";
}

function mod10CheckDigit(bc) {
  bc = bc.replace(/[^0-9]+/g,'');
  total = 0;
  for (i=bc.length-3; i>=0; i=i-2) {
    temp = parseInt(bc.substr(i,1));
    total += temp;
  }
  for (i=bc.length-2; i>=0; i=i-2) {
      temp = parseInt(bc.substr(i,1)) * 3;
      total = total + temp;
  }
  modDigit = (10 - total % 10) % 10;
  is_right = parseInt(bc.substr(bc.length-1,1)) == modDigit;
  corrected = bc.substr(0,bc.length-1) + modDigit;
  return {is_right:is_right,corrected:corrected,cd:modDigit,meat:bc.substr(0,bc.length-1)};
}
$.validator.addMethod("check_digit", function(value,element,param) {
  cd = mod10CheckDigit(value);
  if(!cd.is_right){
    this.settings.messages[element.name] = "Invalid check digit. Corrected number is: "
    + cd.meat
    + "<u>" + cd.cd + "</u>";
  }
	return cd.is_right;
});

$.validator.addMethod("isbn_prefix", function(value,element,param) {
  return isbnPrefix(value);
},"ISBN-13 must start with 978");

$(document).ready(function() {
  $("#main").validate({meta: "validate",
  		errorLabelContainer: $("#main td.wrong")
  	});
});
