(function ( $ ) {
	"use strict";
	function cybersource_soap_event_handler(){

		var $checkout_form 		= $( 'form.checkout, form#order_review, form#add_payment_method' ),
			$prefix_ 			= 'cybsawm',
	    	$cardnumber    		= $( '#'+ $prefix_ +'-card-number' ).val(),
	        $card_expiry   		= $.payment.cardExpiryVal( $( '#'+ $prefix_ +'-card-expiry' ).val() ),
	        $card_cvc 			= $("#" + $prefix_ + '-card-cvc').val(),
	        $card_expiry_month 	= $card_expiry.month,
	        $card_expiry_year 	= $card_expiry.year;

	        $cardnumber 		= $cardnumber.replace( /\s/g, '' );
	        $card_cvc 			= $card_cvc.replace( /\s/g, '' );

	    var $data = {
	    		'cardnumber' : $cardnumber,
	    		'card_cvc'   : $card_cvc,
	    		'expiry_m'   : $card_expiry_month,
	    		'expiry_y'   : $card_expiry_year
	     };   

	     cybsawm_handle_build_card($data);

	     return false;

	}

	function cybsawm_handle_build_card( params ) {
   
	   var	$form  		= $( 'form.checkout, form#order_review, form#add_payment_method' ),
	       	$cybsawm  	= $( "#wc-cybsawm-cc-form" );

			$cybsawm.append( '<input type="hidden" class="cybsawm-cardnumber" name="cybsawm-cardnumber" value="' + params.cardnumber + '"/>' );
			$cybsawm.append( '<input type="hidden" class="cybsawm-card_cvc" name="cybsawm-card_cvc" value="' + params.card_cvc + '"/>' );
			$cybsawm.append( '<input type="hidden" class="cybsawm-expiry_m" name="cybsawm-expiry_m" value="' + params.expiry_m + '"/>' );
			$cybsawm.append( '<input type="hidden" class="cybsawm-expiry_y" name="cybsawm-expiry_y" value="' + params.expiry_y + '"/>' );
	    
	    $form.submit();

	 }

	jQuery( document ).ready( function( $ ) {

		$( document.body ).on( 'checkout_error', function () {
	       $( '.cybsawm-cardnumber' ).remove();
	       $( '.cybsawm-card_cvc' ).remove();
	       $( '.cybsawm-expiry_m' ).remove();
	       $( '.cybsawm-expiry_y' ).remove();
	    });

	    $( "body" ).on( 'click', '#place_order', function( e ){
	        if (  $( '#payment_method_cybsawm' ).is( ':checked' ) ) {
		          cybersource_soap_event_handler();
		          return false;    
	        }

	    });

	    $( 'form.checkout, form#order_review, form#add_payment_method' ).on( 'change', '#wc-cybsawm-cc-form input', function() {
	      	$( '.cybsawm-cc-form-cardnumber' ).remove();
	       	$( '.cybsawm-cc-form-card_cvc' ).remove();
	       	$( '.cybsawm-cc-form-expiry_m' ).remove();
	       	$( '.cybsawm-cc-form-expiry_y' ).remove();
	    });

	});


}( jQuery ) );