jQuery( function($) {

	jQuery(document).on( 'click', '.wre-stripe-pay-button', function(){

		var $form  = jQuery(this).prev('form');
		var $token = $form.find('input.stripe_token');

		if ( $token.val() )
			return true;

		var token_action = function( res ) {
			$form.find('input.stripe_token').remove();
			$form.append("<input type='hidden' class='stripe_token' name='stripe_token' value='" + res.id + "'/>");
			$form.find('#wre_listing_preview_submit_button').trigger( "click" );
		};

		authorize_stripe( token_action, stripe_checkout_params.amount );

		return false;
    });

	jQuery( document ).on('click', '.wre-stripe-subscribe-button', function(e){
		e.preventDefault();
		var package_id = jQuery(this).attr( 'data-package' );
		var amount = parseInt(jQuery(this).attr( 'data-package-amount' )*100);
		var token_action = function( res ) {
			if( res != undefined ) {
				jQuery('body').find('.wre-overlay-blocker').addClass('in');
				jQuery.ajax({
					type: 'POST',
					url: stripe_checkout_params.ajax_url,
					data: {
						'action': 'wre_new_subscriber',
						'package': package_id,
						'token_id': res.id
					},
					success: function (response) {
						jQuery('body').find('.wre-overlay-blocker').removeClass('in');
						if( response.flag ) {
							window.location.href = response.redirect_url;
						} else {
							alert( response.message );
						}
					}
				});
			}
		};

		authorize_stripe( token_action, amount );

		return false;
	});
	
	function authorize_stripe( token_action, amount ) {
		StripeCheckout.open({
			key:			stripe_checkout_params.key,
			billingAddress:	false,
			name:			stripe_checkout_params.name,
			amount:			amount,
			panelLabel:		stripe_checkout_params.label,
			currency:		stripe_checkout_params.currency,
			email:			stripe_checkout_params.email,
			token:			token_action
		});
	}
	jQuery( '.wc-credit-card-form-card-number' ).payment( 'formatCardNumber' );
	jQuery( '.wc-credit-card-form-card-expiry' ).payment( 'formatCardExpiry' );
	jQuery( '.wc-credit-card-form-card-cvc' ).payment( 'formatCardCVC' );

});