/*global enableSubmitButton, disableSubmitButton, createApplicantFormRules, validatePaymentForm */
// global store for most recent server side error messages
var lastServerErrorMessages = {};

$(document).ready(function() {
  var paymentForm = $('#payment_info');
	enableSubmitButton();
  paymentForm.submit(function() {
    disableSubmitButton();
    
    var applicantForm = $('#new_applicant');
    $.post("/applicant_storage", applicantForm.serialize(), function(data) {
      var paymentFormValid = validatePaymentForm(paymentForm);
      var applicantFormValid = data.success;

      if (applicantFormValid) {
        lastServerErrorMessages = {};
      } else {
        var error_messages = {};
        $.each(data.error_messages, function(index, pair) {
          error_messages[pair[0]] = pair[1];
        });
        if (error_messages.phone) {
          error_messages.phone_1i = "";
          error_messages.phone_2i = "";
          error_messages.phone_3i = error_messages.phone;
        }
        if (error_messages.billing_phone) {
          error_messages.billing_phone_1i = "";
          error_messages.billing_phone_2i = "";
          error_messages.billing_phone_3i = error_messages.billing_phone;
        }
        lastServerErrorMessages = error_messages;
      }
      
      applicantForm.validate({
        rules: createApplicantFormRules(applicantForm)
      });
      applicantForm.valid(); 
      
      if (paymentFormValid && applicantFormValid) {
        $('#token').val(data.tc_token);
        $('#amount').val(data.quote_amount);
        paymentForm.unbind('submit'); // unbind our custom handler


        var month = $('#expdate__2i').val();

        if(month.length < 2) {
          month = "0" + month;
        }

        var year = $('#expdate__1i').val().substr(2,2);

        $("#payment_info").append('<input type="hidden" name="exp" id="exp" value="'+ month + year +'">');

        $('#payment_terms_and_conditions').remove();
        $('#cardtype').remove();
        $('#expdate__3i').remove();
        $('#expdate__2i').remove();
        $('#expdate__1i').remove();

        paymentForm.submit();
      } else {
        enableSubmitButton();
				$(document).scrollTop(0);
      }
      
    });
    return false;
  });
  
  // helper function to fire validation on field2 when cardtype changes
  $('#cardtype').change(function(){
    paymentForm.validate().element('#number');
  });
  // helper function to fire validation on field2 when cardtype changes
  $('#expdate__1i').change(function(){
    paymentForm.validate().element('#expdate__2i');
  });
	
	//hide labels for filled LP form fields on reload
	$("input.covered").each(function(){
		if($(this).val() !== "")
			$(this).siblings("label").css("text-indent",-5000);
	});
	
	//Function to remove input label when user enters an input field
	$("input.covered").focus(function(){		
		var label = $(this).siblings("label");
		label.css("text-indent", -5000);
	});
	
	//Function to return label to input if user leaves input blank
	$("input.covered").focusout(function(){		
		var label = $(this).siblings("label");
		if($(this).val() === "")
			label.css("text-indent", 0);
	});
	
  $("#form_billing_info_the_same").click(function() {
    var check = this;
    $("[id*='form_billing_']").each(function (i) {
      var shipping = $("#" + $(this).attr("id").replace(/billing_/, ""));
      if($(check).attr("checked") === true) {
        $(this).val(shipping.val());
      } else {
        if ($(shipping).val() === $(this).val()) {
          if ($(this).attr("tagName") === 'SELECT') {
            $(this).val($(":first-child", this).val());
          } else {
            $(this).val('');
          }
        }
      }
    });
  });
});

function createApplicantFormRules(applicantForm) {
  var retval = {};
  applicantForm.find("input,select,checkbox").each(function(index, element) {
    retval[element.name] = {
      displaymessage: function() {
        return lastServerErrorMessages[element.id.substring("form_".length)];
      }
    };
  });
  return retval;
}

function disableSubmitButton() {
  $('#payment_info_submit').attr('disabled', true);
  $('#loading_msg').show();
}

function enableSubmitButton() {
  $('#payment_info_submit').attr('disabled', false);
  $('#loading_msg').hide();
}

function validatePaymentForm(paymentForm) {
  var retval = null;
  paymentForm.validate({
    rules: {
      cc: {creditcard2: function(){ return $("#cardtype").val(); }},
      "payment[terms_and_conditions]": "required",
      "expdate[(2i)]": {expiredate: function(){ return [$("#expdate__1i").val(), $("#expdate__2i").val()];} }
    },
    messages: {
      "payment[terms_and_conditions]": "You must accept the agreement",
      "expdate[(2i)]": "CC expired"
    }
  });
  retval = paymentForm.valid();
  return retval;  
}

jQuery.validator.addMethod("expiredate", function(value, element, params) {
  var now = new Date();
 return (params[0] !== now.getFullYear()) || (params[1] >= (now.getMonth() + 1));
}, jQuery.format("Credit Card Has Expired"));


jQuery.validator.addMethod("displaymessage", function(value, element, params) {
  if (params === undefined) {
    return true;
  } else {
    return false;
  }
}, jQuery.format("{0}"));

