var matches = [];
// ------  formats for appraiser license in each state  ---------
//       using subpaterns to construct a regex to match the returned licenses
var licenseRE = {
  AL: [/^AL[GR][0-9]{5}$/, "a G or an R followed by 5 digits"],
  AZ: [/^AZ[0-9]{5}$/, "5 digits"],
  AR: [/^AR([0-9]{2}|CG|CR)[0-9]{4}$/, "a CG or CR, followed by 4 digits"],
  CA: [/^CAA[GR][0-9]{6}$/, "an AG or AR followed by 6 digits"],
  CO: [/^CO(AL|CG|CR)*(1|4)*([0-9]{7,8})$/, "AL, CG, or CR followed by 7 or 8 digits"],
  CT: [/^CTRC[GR]([0-9]{1,7})%/, "R, then CG or CR followed by up to 7 digits"],
  DE: [/^DEX[12]([0-9]{6,8})$/, "X1 or X2 followed by 6 to 8 digits"],
  FL: [/^FLR[DZ]([0-9]{2,7})$/, "RD or RZ followed by up to 7 digits"],
  GA: [/^GA(C[GR])*([0-9]{4,8})$/, "4 to 8 digits"],
  ID: [/^IDC[GR]A([0-9]{1,4})$/, "CG or CR, then A followed by up to 4 digits"],
  IL: [/^IL55[63][0-9]{6}$/, "55, then 6 or 3, followed by 6 digits"],
  IN: [/^INC[GR][0-9]{8}$/, "CG or CR followed by 8 digits"],
  IA: [/^IAC[GR][0-9]{5}$/, "CG or CR followed by 5 digits"],
  KS: [/^KS([0-9]{1,4})$/, "up to 4 digits only"],
  KY: [/^KY([0-9]{1,4})$/, "up to 4 digits only"],
  LA: [/^LA([GR])*([0-9]{1,4})$/, "G or R followed by up to 4 digits"],
  ME: [/^MEC[GR]([0-9]{3,12})$/, "CG or CR followed by up to 12 digits"],
  MD: [/^MD[2-4]*([0-9]{2,7})$/, "2, 3, or 4, followed by up to 7 digits"],
  MA: [/^MA([0-9]{1,7})$/, "up to 7 digits"],
  MI: [/^MI1201[0-9]{6}$/, "11201 followed by 6 digits"],
  MN: [/^MN(AP)*[124]0([0-9]{5,6})$/, "1, 2, or 4, followed by 0, then 5 or 6 digits"],
  MS: [/^MS[GR]A([0-9]{1,5})$/, "GA or RA, then up to 5 digits"],
  MO: [/^MO(1999|200[0-9]|RA)([0-9]{4,6})$/, "4 to 6 digits"],
  MT: [/^MT([0-9]{1,4})$/, "up to 4 digits"],
  NE: [/^NEC[GR][0-9]{6}R$/, "CG or CR, followed by 6 digits, then an R"],
  NV: [/^NVA[0-9]{7}C[GR]$/, "7 digits followed by CG or CR"],
  NH: [/^NHC[GR]([0-9]{1,3})$/, "CG or CR, followed by up to 3 digits"],
  NJ: [/^NJ42R[ACG][0-9]{6}00$/, "42, then RA or RC or RG, followed by 6 digits, then 00"],
  NM: [/^NM([0-9]{1,6})[GR]$/, "up to 6 digits, then G or R"],
  NY: [/^NY4[567]0000[0-9]{5}$/, "450000, 460000, or 470000 followed by 5 digits"],
  NC: [/^NCA([0-9]{1,4})$/, "A followed by up to 4 digits"],
  ND: [/^NDC[GR]([0-9]{1,4})$/, "CG or CR followed by up to 4 digits"],
  OH: [/^OH(200[0-9])*[0-9]{6}$/, "6 digits (do not include the year)"],
  OK: [/^OK[0-9]{5}C[GR]A$/, "5 digits followed by CG or CR followed by A"],
  OR: [/^ORC[0R][0-9]{5}$/, "C0 or CR followed by 5 digits"],
  PA: [/^PA(GA|RL)[0-9]{6}L$/, "GA or RL followed by 6 digits followed by L"],
  RI: [/^RIA[0-9]{5}[GR]$/, "A followed by 5 digits followed by G or R"],
  SC: [/^SC(CR|CG|L)*([0-9]{1,5})$/, "CR, CG or L followed by up to 5 digits"],
  SD: [/^SD([0-9]{3,4})C[GR]$/, "3 or 4 digits followed by CG or CR"],
  TN: [/^TN(CR|CG)*([0-9]{1,8})$/, "CR or CG followed by up to 8 digits"],
  TX: [/^TX[0-9]{7}[GR]$/, "7 digits followed by G or R"],
  UT: [/^UT([0-9]{5,7})C[GR]00$/, "5 to 7 digits, then CG or CR, then 00"],
  VT: [/^VT(79|80)([0-9]{7,9})$/, "79 or 80 followed by 7 to 9 digits"],
  VA: [/^VA40010[0-9]{5}$/, "40010 followed by 5 digits"],
  WA: [/^WA1[0-9]{6}$/, "1 followed by 6 digits"],
  WV: [/^WVC[GR]([0-9]{3,4})$/, "CG or CR followed by up to 4 digits"],
  WI: [/^WI([0-9]{1,4})(009|010)*$/, "up to 4 digits"],
  WY: [/^WY([0-9]{1,4})$/, "up to 4 digits"]  
};

$(function() {
  $("form[name=AccountCreate], form[name=AccountSubForm]").bind("change", function(e) {
    if (( this.elements['FirstName'].value > "" ) && 
        ( this.elements['LastName'].value > "" ) && 
        ( this.elements['City'].value > "" ) && 
        ( this.elements['State'].value > "" )) {
      var form = $(this);
      $.getJSON(form.attr("action"), $(":input[type!=password]", form).serialize(), function(data) {
        matches = data;
        displayAppraiser();
      });
    }
    displayAppraiser();
  }).trigger("change");
  if ( $("input[name=IsAppraiser]:checked").length == 0 ) {
    $(".Appraiser").hide();
  }
  $("input[name=LicenseNumber], input[name=LicenseState]").bind("change", checkLicense);
  $("#IsAppraiserField").bind("click", function(e) {
    $(this).data("manual", true);
    if ( this.checked ) $(".Appraiser").show();
    else $(".Appraiser").hide(); 
  });
});

function displayAppraiser() {
  if (( matches.length > 0 ) || 
      ( /apprais/i.test($("input[name=Company]").val()) ) || 
      ( /apprais/i.test($("input[name=Title]").val()) )) {
    var cb = $("#IsAppraiserField");
    if ( ! cb.data("manual") ) {
      cb[0].checked = true;
      $(".Appraiser").show();
    }
  }
}

function checkLicense(e) {
  var state = $("input[name=LicenseState]").val().toUpperCase();
  var number = $("input[name=LicenseNumber]").val().toUpperCase();
  var matched = false;
  if (( state > "" ) && ( number > "" )) {
    if ( number.substr(0,2) )
    if ( licenseRE[state] ) {
      var all = state + number;
      if ( ! licenseRE[state][0].test(all) ) {
        showError("Please enter " + licenseRE[state][1]);
        return false;
      } else {
        showError("");
      }
    } else {
      showError("Please enter a two letter state code (like \"MI\")");
      return false;
    }
    matched = licenseMatch(state, number);
    if ( matched ) {
      $(this).val(matched);
      matched = true;
    }
  }
  return matched;
}

function licenseMatch(state, number) {
  var parts, reStr, re, i, len, replacement;
  // prereqs
  if ( matches.length === 0 ) return false;
  if ( ! licenseRE[state] ) return false;
  parts = licenseRE[state][0].exec(state+number);
  if (( ! parts ) || ( parts.length === 0 )) return false;

  reStr = parts[0];
  for ( i = 1, len = parts.length; i < len; i++ ) {
    replacement = parts[i];
    if ( /^[0-9]$/.test(parts[i]) ) replacement = parts[i].ltrim("0");
    reStr = reStr.replace(parts[i], ".*" + parts[i] + ".*");
  }
  // clean up by removing dupes and the one at the end if any
  reStr = reStr.replace(".*.*", ".*");
  if ( reStr.slice(-2) === ".*") reStr = reStr.slice(0, -2);
  re = new RegExp("^" + reStr + "$");
  for ( i = 0, len = matches.length; i < len; i++ ) {
    // if matches, strip state code and return rest
    if ( re.test(matches[i].LicenseNumber) ) {
      if ( $("#EmailField").val() == matches[i].Email ) {
        showError("Your license has been validated");
      } else {
        if ( matches[i].Email == "" ) {
          matches[i].Email = "unknown";
        }
        showError("We have the license number you entered on file, but the email address for this license is " + matches[i].Email + ".  We will have to manually validate your account.");
      }
      return matches[i].LicenseNumber.substring(2);
    }
  }
  showError("We don't have that license on file.");
  return number;
}


function showError(error) {
  $("#LicenseStatus").text(error);
}

String.prototype.ltrim = function(stripChar) {
  var l = 0;
  var len = this.length;
  while (( l < len ) && ( this[l] === stripChar )) {
    l++;
  }
  return this.substring(l, len);
};
