function post(frm) {
  if(validate(frm)) {
    $.ajax({
      type: 'POST',
      url: '/tokens/',
      dataType: 'json',
      data: $(frm).serialize(),
      success: function(data) {
        if(data.success) {
          $("#_aIdx", frm).val(data.token);
          $("#security_code").removeClass("error");
          frm.submit();
        } else {
          $("#security_code").addClass("error");
          alert("The validation code you entered was not correct.  Please re-enter the validation code.");
        }
      }
    });
  }
  return false;
}


function validate(frm) {
  var reqs = $('.required:visible', frm);
  var $first = 0;
  var errors = 0;
  for(i=0; i<reqs.length; i++) {
    $req = $(reqs[i]);
    if(!hasValue($req)) {
      if(!$first) $first = $req;
      $req.addClass('error').change(function() {
        if(hasValue($(this))) {
          $(this).removeClass('error');
        }
      });
      errors++;
    }
  }

  if(errors) {
    alert('Please answer all the required questions.');
    $first.focus();
    return false;
  }

  var fields = $(":input", frm);
  for(i=0; i<fields.length; i++) {
    $field = $(fields[i]);
    if(!isLegit($field)) {
      if(!$first) $first = $field;
      $field.addClass('error').change(function() {
        if(isLegit($(this))) {
          $(this).removeClass('error');
        }
      });
      errors++;
    }
  }

  if(errors) {
    alert('Please remove all inappropriate content.');
    $first.focus();
    return false;
  }

  return true;
}

function hasValue($req) {
  r = false;
  type = $req.attr('type');
  if(type == 'checkbox' || type == 'radio')
    r = $('input[name='+$req.attr('name')+']:checked').length != 0;
  else
    r = $req.val() != '';

  return r;
}

function isLegit($req) {
  val = $req.val();
  bad = val.indexOf("href=") != -1 ||
      val.indexOf("http:") != -1 ||
      val.indexOf("www.") != -1;
  
  if(!bad && $req.attr("name") != "email") {
    bad = val.indexOf(".com") != -1 ||
        val.indexOf(".net") != -1;

  }

  return !bad;
}

