WPADVERTS.Payments.Stripe = {
    PK: null,
    Instance: null,
    Cards: [],
    Nonce: null,
    
    URL: function() {
        if(typeof ajaxurl !== 'undefined' ) {
            return ajaxurl;
        } else if(typeof wpadverts_stripe_main_lang.ajaxurl ) {
            return wpadverts_stripe_main_lang.ajaxurl;
        } else {
            return '/wp-admin/admin-ajax.php';
        }
    }
};

WPADVERTS.Payments.Stripe.Gateway = function() {
    this.PaymentIntentId = null;
    this.RequestIndex = 0;
    this.stripe = Stripe(wpadverts_stripe_main_lang.publishable_key);
    this.card = null;
    
};

WPADVERTS.Payments.Stripe.Gateway.prototype.success = function(response) {
    jQuery(".adverts-tab-content").css("opacity", 1).html(response.html);
    jQuery(".wpadverts-card-errors").hide();
    
    if(response.result == 0) {
        jQuery(".adext-payments-place-order").show();
    }
    
    // Create an instance of Elements.
    var elements = this.stripe.elements();

    // Create an instance of the card Element.
    this.card = elements.create('card');

    // Add an instance of the card Element into the `card-element` <div>.
    this.card.mount('#credit_card');

    // Handle real-time validation errors from the card Element.
    this.card.addEventListener('change', function(event) {
        if (event.error) {
            jQuery(".wpadverts-card-errors").show().text(event.error.message);
        } else {
            jQuery(".wpadverts-card-errors").hide().text("");
        }
    });
    
    var $ = jQuery;
    $(".wpadverts-add-credit-card").click(function(e) {
        e.preventDefault();
        $(".wpadverts-card-details").show();
        $("#card-errors").hide();
        $(".wpadverts-add-credit-card-cancel").show();
        
        $(".wpadverts-add-credit-card").hide();
        $(".wpadverts-credit-card-list").hide();
    });
    
    $(".wpadverts-add-credit-card-cancel").click(function(e) {
        e.preventDefault();
        $(".wpadverts-card-details").hide();
        $("#card-errors").hide();
        $(".wpadverts-add-credit-card-cancel").hide();
        
        $(".wpadverts-add-credit-card").show();
        $(".wpadverts-credit-card-list").show();
    });
    
    WPADVERTS.Payments.Stripe.Cards = [];
    
    $(".wpadverts-credit-card-single").each(function(index, item) {
        WPADVERTS.Payments.Stripe.Cards.push( new WPADVERTS.Payments.Stripe.Card( $(item) ) );
    });
   
};

WPADVERTS.Payments.Stripe.Gateway.prototype.error = function(xhr) {
    jQuery(".adverts-tab-content").css("opacity", 1);
    jQuery(".adext-payments-place-order").show();
    
    var flash = jQuery("<div></div>").addClass("adverts-flash-messages adverts-flash-error");
    var inside = jQuery("<div></div>").addClass("adverts-flash-message-text");
    
    if(typeof xhr.responseJSON !== 'undefined' ) {
        inside.html(xhr.responseJSON.html);
    } else {
        inside.html(xhr.responseText);
    }
    
    flash.append(inside);
    
    jQuery(".adverts-tab-content").prepend( flash );
};

WPADVERTS.Payments.Stripe.Gateway.prototype.place_order = function() {
    
    jQuery(".adverts-tab-content").css("opacity", 0.5);
    jQuery(".adverts-tab-content .adverts-field-error").removeClass("adverts-field-error");
    jQuery(".adverts-tab-content .adverts-field-error-list").remove();
    jQuery(".adverts-tab-content .adverts-flash-messages").remove();
    jQuery(".adext-payments-place-order").hide();
    
    jQuery(".wpadverts-card-errors").hide();
    jQuery(".wpadverts-card-error-text").text("");
    
    var $ = jQuery;
    var data = {
        action: "adext_payments_render",
        gateway: $(".adverts-tab-link.current").data("tab"),
        page_id: $(".adverts-payment-data").data("page-id"),
        listing_id: $(".adverts-payment-data").data("listing-id"),
        object_id: $(".adverts-payment-data").data("object-id"),
        payment_id: $(".adverts-payment-data").data("payment-id"),
        form: $(".adverts-tab-content form").serializeArray()
    };

    $.ajax({
        url: WPADVERTS.Payments.Stripe.URL(),
        context: this,
        type: "post",
        dataType: "json",
        data: data,
        success: jQuery.proxy( this.place_order_success, this ),
        error: jQuery.proxy( this.place_order_error, this )
    });
};

WPADVERTS.Payments.Stripe.Gateway.prototype.place_order_success = function( response) {
    
    var tab = jQuery(".adverts-tab-link.current").data("tab");
    var html = jQuery(response.html);
    
    html.find(".adverts-control-group").each(function(index, item) {
        
        if(jQuery(item).hasClass("adverts-field-name-credit_card")) {
            return;
        }
        
        var classes = jQuery.grep(item.className.split(" "), function(v, i){
               return v.indexOf('adverts-field-name-') === 0;
        }).join();
        
        jQuery(".adverts-tab-content").find("." + classes ).replaceWith(item);
    });

    if(response.result != 1) {
        jQuery(".adverts-tab-content").css("opacity", 1);
        jQuery(".adext-payments-place-order").fadeIn();
        jQuery("ul.adverts-tabs li").unbind("click").css("cursor", "default");
        return;
    }

    var card = jQuery("input[name='_stripe_card']:checked");
    var card_id = card.val();

    if( jQuery(".wpadverts-credit-card-list").is(":visible") && card_id ) {
        this.stripe.handleCardPayment(
            jQuery("#credit_card").data("secret"),
            {
                payment_method: card_id,
                receipt_email: jQuery("#adverts_email").val()
                //save_payment_method: jQuery("#credit_card").is(":visible")
            }
        ).then(jQuery.proxy(this.place_order_handle, this));
    } else {
        this.stripe.handleCardPayment(
            jQuery("#credit_card").data("secret"),
            this.card,
            {
                payment_method_data: {
                    billing_details: {   
                        name: jQuery("#adverts_person").val(),
                        email: jQuery("#adverts_email").val()
                        //phone: '',
                        //address: ''
                    }
                },
                receipt_email: jQuery("#adverts_email").val()
                //save_payment_method: jQuery("#credit_card").is(":visible")
            }
        ).then(jQuery.proxy(this.place_order_handle, this));
    }


    //successCallback( response );
};

WPADVERTS.Payments.Stripe.Gateway.prototype.place_order_error = function( result ) {
    var tab = jQuery(".adverts-tab-link.current").data("tab");

    jQuery(".wpadverts-card-error-text").html(result.statusText);
    jQuery(".wpadverts-card-errors").show().text(result.statusText);
    jQuery(".adverts-tab-content").css("opacity", 1);
    jQuery(".adext-payments-place-order").show();
};

WPADVERTS.Payments.Stripe.Gateway.prototype.place_order_handle = function(result) {
    
    if(!result.error) {
        this.place_order_pending({result: 0, message: '', index: 0, intent_id: result.paymentIntent.id});
        return;
    }
    
    jQuery(".wpadverts-card-error-text").html(result.error.message);
    jQuery(".wpadverts-card-errors").show().text(result.error.message);
    jQuery(".adverts-tab-content").css("opacity", 1);
    jQuery(".adext-payments-place-order").show();

};

WPADVERTS.Payments.Stripe.Gateway.prototype.place_order_pending = function( response ) {
    
    jQuery(".adext-payments-place-order").hide();

    if( response.result == 0 ) {
        if( response.index === 1 ) {
            jQuery(".adverts-tab-content").css("opacity", 1).html(response.message);
        }
        setTimeout( jQuery.proxy( this.place_order_pending_ajax, this ), 1000*parseInt(response.index), response );
    } else if( response.result == 1 ) {
        jQuery(".adverts-tab-content").css("opacity", 1).html(response.message);
        jQuery(".wpadverts-card-errors").hide();
    } else {
        jQuery(".adverts-tab-content").css("opacity", 1).html(response.message);
        jQuery(".wpadverts-card-errors").hide();
    }
};

WPADVERTS.Payments.Stripe.Gateway.prototype.place_order_pending_ajax = function( response ) {
    var data = {
        action: "wpadverts-stripe-complete",
        payment_intent_id: response.intent_id,
        index: response.index
    };
    jQuery.ajax({
        url: WPADVERTS.Payments.Stripe.URL(),
        data: data,
        type: "post",
        dataType: "json",
        success: jQuery.proxy( this.place_order_pending, this ),
        error: jQuery.proxy( this.place_order_complete_error, this )
    });    
};

WPADVERTS.Payments.Stripe.Gateway.prototype.place_order_complete_success = function() {
    
};

WPADVERTS.Payments.Stripe.Gateway.prototype.place_order_complete_error = function( response ) {
    alert( response.responseStatus + "\n" + response.responseText );
};

WPADVERTS.Payments.Stripe.Card = function( item ) {
    this.item = item;

    this.radio = this.item.find("input[type=radio]");
    this.loader = this.item.find(".wpadverts-stripe-cc-actions-loader");
    
    this.card_actions = this.item.find(".wpadverts-stripe-cc-actions");

    this.card_default = this.item.find(".wpadverts-stripe-cc-actions-default");
    this.card_trash = this.item.find(".wpadverts-stripe-cc-actions-trash");
    
    this.card_trash_confirm = this.item.find(".wpadverts-stripe-cc-actions-trash-confirm");
    this.card_trash_confirm_yes = this.item.find(".wpadverts-stripe-cc-actions-trash-confirm-yes");
    this.card_trash_confirm_no = this.item.find(".wpadverts-stripe-cc-actions-trash-confirm-no");
    
    
    this.card_trash.click(jQuery.proxy(this.card_trash_click, this));
    this.card_trash_confirm_yes.click(jQuery.proxy(this.card_trash_confirm_yes_click, this));
    this.card_trash_confirm_no.click(jQuery.proxy(this.card_trash_confirm_no_click, this));
    
    this.card_default.click(jQuery.proxy(this.card_default_click, this));
    
    this.card_trash_confirm.hide();
    this.loader.hide();
};

WPADVERTS.Payments.Stripe.Card.prototype.card_trash_click = function(e) {
    if(typeof e !== 'undefined') {
        e.preventDefault();
    }
    this.card_actions.hide();
    this.card_trash_confirm.show();
    this.loader.hide();
};

WPADVERTS.Payments.Stripe.Card.prototype.card_trash_confirm_no_click = function(e) {
    if(typeof e !== 'undefined') {
        e.preventDefault();
    }
    this.card_actions.show();
    this.card_trash_confirm.hide();
    this.loader.hide();
};

WPADVERTS.Payments.Stripe.Card.prototype.card_trash_confirm_yes_click = function(e) {
    if(typeof e !== 'undefined') {
        e.preventDefault();
    }
    
    this.card_trash_confirm.hide();
    this.loader.show();
    
    var data = {
        action: 'wpadverts-stripe-card-trash',
        nonce: _wpadverts_stripe_cc_nonce,
        card_id: this.radio.attr("value")
    };
    
    jQuery.ajax({
        url: WPADVERTS.Payments.Stripe.URL(),
        data: data,
        dataType: 'json',
        type: 'post',
        success: jQuery.proxy(this.card_trash_ajax_success, this),
        error: jQuery.proxy(this.card_trash_ajax_error, this)
    });
};

WPADVERTS.Payments.Stripe.Card.prototype.card_default_click = function(e) {
    if(typeof e !== 'undefined') {
        e.preventDefault();
    }
    
    this.card_actions.hide();
    this.loader.show();
    
    var data = {
        action: 'wpadverts-stripe-card-source',
        nonce: _wpadverts_stripe_cc_nonce,
        card_id: this.radio.attr("value")
    };
    
    jQuery.ajax({
        url: WPADVERTS.Payments.Stripe.URL(),
        data: data,
        dataType: 'json',
        type: 'post',
        success: jQuery.proxy(this.card_default_success, this),
        error: jQuery.proxy(this.ajax_error, this)
    });
};

WPADVERTS.Payments.Stripe.Card.prototype.card_default_success = function(response) {
    
    this.card_actions.show();
    this.loader.hide();
    
    if(typeof response !== 'object') {
        this.ajax_error(response);
        return;
    }
    
    if(response.result != 1) {
        alert(response.message)
        return;
    }
    
    var card_id = this.radio.attr("value");
    
    jQuery.each(WPADVERTS.Payments.Stripe.Cards, function(index, item) {
        item.toggle_default( card_id );
    });
};

WPADVERTS.Payments.Stripe.Card.prototype.card_trash_ajax_success = function(response) {
    
    this.card_trash_confirm_no_click();
    
    if(typeof response !== 'object') {
        this.ajax_error(response);
        return;
    }
    
    if(response.result != 1) {
        alert(response.message)
        return;
    }
    
    this.item.fadeOut("fast").remove();
};

WPADVERTS.Payments.Stripe.Card.prototype.ajax_error = function(response) {
    
};

WPADVERTS.Payments.Stripe.Card.prototype.toggle_default = function(card_id) {
    var card = this.radio.attr("value");
    if(card == card_id) {
        this.item.addClass("wpadverts-card-is-default");
    } else {
        this.item.removeClass("wpadverts-card-is-default");
    }
};

WPADVERTS.Payments.Engine.stripe = new WPADVERTS.Payments.Stripe.Gateway();

jQuery(function($) {

});