/*
    WooCommerce Extension Script
*/

(function($) {
    
    // $(document).ready(function() {
    $(function() {
        greyd_woo.init();
        console.log('WooCommerce Script: loaded');
    } );

} )(jQuery);

var greyd_woo = new function() {

    // Constructor
    this.init = function() {
        this.addEvents();
    },
    
    this.addEvents = function() {
        // checkout page
        if ($('body').hasClass('woocommerce-checkout')) {
            this.addSingleCountryInput();
        }
        
        $('[href^="_woo_ajax"]').each(function(){
            greyd_woo.formatAjaxButton($(this));
        });
        
        $("[onclick^='window.open(\"_woo_ajax']").each(function(){
            greyd_woo.formatAjaxButton($(this), 'onclick');
        });
            
        $( '.greyd_woo_ajax' ).on("click", function(e) {
            e.stopPropagation();
            console.log($(this).data('ajax'));
            greyd_woo.ajax.apply(this, $(this).data('ajax'));
        });
        
        // console.log(ajax_details);
        // this.api();
    },
    
    // if only 1 country is selectable --> add disabled input
    this.addSingleCountryInput = function() {
        var single_country = $('#billing_country_field .woocommerce-input-wrapper > strong:first-child');
        if (single_country.length > 0) {
            single_country.after('<div class="input disabled">'+single_country.text()+'</div>');
            single_country.remove();
        }
    }
    
    this.formatAjaxButton = function(button, attr='href') {
        var href = button.attr(attr).replace(/_/g, '').toString();
        var data = href.split('|');
        data[0] = data[0].indexOf('=') > -1 ? data[0].split('=')[1].toString() : button.closest('.search_result').data('post');
        // console.log(data);
        
        button.removeAttr(attr);
        button.addClass('greyd_woo_ajax');
        button.data('ajax', data);
        var loader = '<span class="greyd_loader loading"></span><span class="greyd_loader success"></span><span class="greyd_loader fail"></span>';
        if (attr === 'href') {
            if ( button.parent(".wp-block-greyd-buttons").length ) {
                button.append(loader);
            } else {
                button.children(':first-child').append(loader);
            }
        }
        else
            button.children('.vc-content-box').append(loader);
        // console.log(button.data('ajax'));
    }
    
    this.ajaxTimeout = '';
    this.ajax = function(id, redirect='default', not_twice=false, clear=false) {
        
        // ID
        // product post-id
        if (typeof id === 'undefined' || id.length === 0) return;
        
        // REDIRECT
        // false | default | shop | cart | checkout | http://www.google.de...
        redirect = redirect === 'false' ? false : redirect; 
        
        // NOT_TWICE
        // true | false -> disbales being added twice
        not_twice = not_twice === '1' || not_twice === 'true' ? true : false;
        
        // CLEAR
        // clears cart before adding (good for simple landingpages)
        clear = clear === '1' || clear === 'true' ? true : false;
        
        var button = $(this);
        if ( button.hasClass('loading') || button.hasClass('success') ) return;
        button.addClass('loading');
        
        // custom button
        var inner = button.children();
        if (typeof inner.attr('onmouseover') !== 'undefined' && inner.attr('onmouseover') !== false) {
            var atts = {};
            atts.color = inner.css('color');
            atts.onmouseover = inner.attr('onmouseover');
            atts.onmouseout = inner.attr('onmouseout');
            inner.removeAttr('onmouseover');
            inner.removeAttr('onmouseout');
            inner.css('color', 'transparent');
        }
        
        $.ajax({
            type: "POST",
            url: ajax_details.ajax_url,
            data: {
                'action': 'greyd_woo_ajax',
                '_ajax_nonce': ajax_details.nonce,
                'data': {
                    'id': id,
                    'not_twice': not_twice,
                    'clear': clear
                }
            },
            success: function(response) {
                button.removeClass('loading');
                
                if (response.indexOf('error::') > -1) {
                    console.warn( response );
                    button.addClass('fail');
                    greyd_woo.ajaxTimeout = setTimeout(function(){ greyd_woo.resetButton(button, atts); }, 1000);
                }
                else {
                    console.info( response );
                    button.addClass('success');
                    
                    // update cart nag
                    var new_count = response.split('::')[1];
                    
                    if ( $('.greyd_cart_nav_item'.length)) {
                        if ( !$('.greyd_cart_nav_item').find('.woo_cart_count').length ) {
                            $('.greyd_cart_nav_item .cart-contents').append("<span class='woo_cart_count'></span>");
                        }
                        var count_item = $('.greyd_cart_nav_item .woo_cart_count');
                        $('.greyd_cart_nav_item').removeClass('hidden');
                        var transform = count_item.css('transform');
                        count_item.css('transform', transform + ' translateY(-12px) scale(1.2)');
                        count_item.html(new_count);
                        setTimeout(function() { count_item.css('transform', transform); }, 200);
                    }
                    
                    // redirect
                    if (redirect === 'default') {
                        if (ajax_details.default_redirect === "yes")
                            redirect = 'cart';
                        else
                            redirect = false;
                    }
                    var link = '';
                    if (redirect === 'shop' || redirect === 'cart' || redirect === 'checkout')
                        link = ajax_details[redirect];
                    else
                        link = redirect;
                    if (redirect !== false) {
                        // console.log('redirect to: '+link);
                        window.location.href = link;
                    } else{
                        greyd_woo.ajaxTimeout = setTimeout(function(){ greyd_woo.resetButton(button, atts); }, 1000);
                    } 
                }
            }
        });
        
    }
    
    this.resetButton = function (button, atts={}) {
        button.removeClass('loading fail success');
        
        var inner = button.children();
        $.each(atts, function(key, val) {
            if (key === 'color')
                inner.css('color', val);
            else
                button.attr(key, val);
        });
    }
};
