jQuery(function($){

  var handleResponse = function ( response ) {

    if (response.status_code === 201) {
      
      var fundingInstrument = response.cards != null ? response.cards[0] : response.bank_accounts[0];

      var data = {
        action : 'app_bp_save_bank_account',
        uri : fundingInstrument.href,
      };

      jQuery.get( window.ap_bp_ajaxurl, data, function( response ){
          location.reload(true);
      } );
    } else {
      $( '#bp-error' ).text( response.message );
    }
  };

  var submitHandler = function() {
    
    var account = {
      'name'           : $('#bp-account-holder').val(),
      'routing_number' : $('#bp-account-routing').val(),
      'account_number' : $('#bp-account-number').val(),
    };

    window.balanced.bankAccount.create( account, handleResponse );
    return false;
  }

  $.validator.addMethod('isRoutingNumberValid', function( value, element ) {
    return window.balanced.bankAccount.isRoutingNumberValid( value )
  }, 'Bad Routing Number' );

  var messages = window.app_bp;
  if( $('#bp-account-holder').length > 0 ) {
    $('#main form').validate({ 
      'submitHandler' : submitHandler,
    });
  }

});


