/**
 * Created by alex on 07/06/2017.
 */

/*
 Credit Card manager: Sets a keyup and paste event on the element passed to this class and then triggers the currency rate function once the digit threshold is reached
 */
function CreditCardManager( element ) {
    var self = this;

    self.creditCard = $( element );
    // TODO - We might have to consider setting the threshold based on the tax service used
    self.digitThreshold = 6; // Threshold of the number of digits required for the tax service.
    self.sent = false; // Whether we sent the credit
    self.creditCardDigits = null;

    // Send credit
    send = function( message ) {
        // If we have not sent the credit card and we have the amount of digits set by the digit threshold then send it and set the send flag to true
        // If the send flag is set and the number of digits falls below the digit threshold the reset the sent flag so that when we resend the credit
        // card once the digit threshold is reaced again
        if( !self.sent && message.length >= self.digitThreshold ) {
            self.creditCardDigits = message.substring( 0, self.digitThreshold );
            CheckoutPageManager.getCurrencyRate();
            self.sent = true;
        } else if( self.sent && message.length < self.digitThreshold ) {
            self.sent = false;
        }
    };

    // KeyUp Event: Get the credit card and send it
    keyup = function( e ) {

        var message = $( this ).val().replace( /\s/g, '' );

        send( message );
    };

    // Paste event: Get the value pasted and send it
    paste = function( e ) {
        var message = e.originalEvent.clipboardData.getData( 'text' );

        self.sent = false;
        send( message );
    };

    // Get the credit card
    self.getCreditCard = function() {
        return self.creditCardDigits;
    };

    self.creditCard.on( "keyup", keyup );
    self.creditCard.on( "paste", paste );
}
