$(document).ready(function() {
  $("input.phone").maskinput("(999) 999-9999");
  $("input.zip").maskinput("99999");

  $.validator.addMethod("ccexp", function(value, element, params) {
    var minMonth = new Date().getMonth() + 1;
    var minYear = new Date().getFullYear();

    var year = $(params.year);
    var month = $(params.month);

    if ((year.val() > minYear && month.val() != '') || (month.val() >= minMonth && year.val() == minYear)) {
      return true;
    } else {
      return false;
    }
  }, "Your Credit Card Expiration date is invalid.");

  $.validator.addMethod("termCheck", function(value, element) {
    if (element.checked) {
      return true;
    } else {
      alert("You must agree to the terms and conditions before submitting the form!");
      return false;
    }
  }, "You must agree to the terms and conditions before submitting the form!");

  $.validator.addClassRules("ccexp", {
    ccexp: { month: '#signup_exp_month', year: '#signup_exp_year' }
  });

  $.validator.addClassRules("termCheck", {
    termCheck: true
  });

  $(".validForm").validate({
    rules: {
      "signup[credit_card]": { required: true, digits: true, minlength: 15, maxlength: 16 },
      "signup[password_confirmation]": { equalTo: '#signup_password' }
    },
    messages: {
      "signup[credit_card]": { digits: "Invalid Credit Card" },
      "signup[password_confirmation]": { equalTo: "Passwords do not match" },
      'agree': ""
    },
    errorElement: "div",
    wrapper: "div",  // a wrapper around the error message
    errorPlacement: function(error, element) {
      if ($(element).attr('name') != 'agree') {
        var offset = 0;

        if ($(element).attr('name') == 'ccexp') {
          offset = 85;
        }

        var top = 18;
        var left = 6 + element.outerWidth() + offset;

        error.insertAfter(element);
        error.addClass('message');  // add a class to the wrapper

        error.css('position', 'absolute');

        error.css('left', left);
        error.css('top', top);
      }
    },
    submitHandler: function(form) {
      alert('Please Wait...Processing your order. This may take a moment.');

      form.submit();
    }
  });
});
