$.validator.addMethod("zip_code", function(value, element) {
  return this.optional(element) || /^(\d{5})(-\d{4})?$/.test(value);
}, "Must be a valid zip code");

$.validator.addMethod("first_name", function(value, element) {
  return this.optional(element) || !(/^First Name\*?$/).test(value);
}, "First Name*");

$.validator.addMethod("last_name", function(value, element) {
  return this.optional(element) || !(/^Last Name\*?$/).test(value);
}, "Last Name*");


function centerModal(){
  //request data for centering
  var windowWidth = document.documentElement.clientWidth;
  var windowHeight = document.documentElement.clientHeight;
  var popupHeight = $("#splash").height();
  var popupWidth = $("#splash").width();
  //centering
  $("#splash").css({
    "position": "absolute",
    "top": windowHeight/2-popupHeight/2,
    "left": windowWidth/2-popupWidth/2,
    "z-index": 10000
  });
	
  $("#background-splash").css({
    "height": windowHeight,
    "opacity": 0.7
  });
}

function hideModal() {
  $('#background-splash').fadeOut('fast');
  $('#splash').fadeOut('fast');		
}

function displayModal() {
  $('#background-splash').show();
  $('#splash').fadeIn('fast');
  centerModal();	
}

$(document).ready(function(){
 var cookie_val = $.cookie('afscme31_signup_modal');
 if (cookie_val) {
   if (cookie_val * 1 < 5) {
     // less than max # of modal displays; increment cookie & launch modal
     $.cookie('afscme31_signup_modal', (cookie_val*1)+1, { expires: 365, path: '/' });
     displayModal();
   }
 }
 else {
   // no cookie; set it and launch modal
   $.cookie('afscme31_signup_modal', '1', { expires: 365, path: '/' });
   displayModal();
 }

 $('#modal-skip').click(function(){
    hideModal();
 });

 $('#modal-signup').validate({
  onkeyup: false,
  rules: {
    Zip: {
	  required: true,
	  zip_code: true
    },
    First_Name: {
	  required: true,
          first_name: true
    },
    Last_Name: {
	  required: true,
          last_name: true
    },
    Email: {
	  required: true,
	  email: true
    }	
  },
    messages: {
      Email: {
	    required: 'Email*',
	    email: 'Invalid Email Address'
	  },
      First_Name: {
	    required: 'First Name Required',
            first_name: 'First Name*'
	  },
      Last_Name: {
	    required: 'Last Name*',
            last_name: 'Last Name*'
	  },
      Zip: {
	    required: 'Zip*',
	    zip_code: 'Zip*'
	  }
    },
  errorPlacement: function(error, element) {
    var msg = $(error).html();
    //console.log(msg);
    $(element).val(msg);
  },
  submitHandler: function(form){
    form.submit();
    $('#to-hide').hide();
    $('#to-show').show();
    $.cookie('afscme31_signup_modal', '11', { expires: 365, path: '/' });
    setTimeout(hideModal,2500);
  }
 });
});
