/**
 * Show right side modal
 */
$(document).ready(function ($) {

    // Popover functionality
    // https://getbootstrap.com/docs/4.3/components/popovers/
        $('#price-on-request-tooltip').popover({
            container: 'body',
            // trigger: 'click focus',
            placement: 'bottom',
            template: '<div class="popover price-on-request-tooltip" role="tooltip"><div class="arrow"></div><div class="popover-header"></div><div class="popover-body"></div></div>'
        });

    // $('#price-on-request-tooltip').click(function(){
    //     console.log('clicked');
    // });

    // console.log('jQuery ver: ' + $().jquery);
    $(document).on('click', '.waranty-info .item', null, function () {
        let modal = $('#sideModal'),
            modal_content = $('.modal-contents .' + $(this).attr('data-type'));

        if (!modal_content.length) {
            return false;
        }

        $("#sideModalLabel2").html(modal_content.find('.title').html());
        modal.find('.modal-body').html(modal_content.find('.content').html());
        modal.modal();
    });

    /**
     * Show produt attributes
     */
    $(document).on('click', '.product-attributes.watches .group-name', null, function () {
        let group = $(this).closest('.group');
        if (!group.hasClass('active')) {
            group.addClass('active');
            group.find('.group-items').slideDown(200);
        } else {
            group.removeClass('active');
            group.find('.group-items').slideUp(200);
        }
    });


    $("#product_images").owlCarousel({
        lazyLoad: true,
        animateOut: 'fadeOut',
        autoplay: false,
        loop: false,
        items: 1,
        dots: true,
        nav: true,
        navText: ['<span class="fa fa-angle-left" aria-hidden="true"></span>', '<span class="fa fa-angle-right" aria-hidden="true"></span>']
    });

    runReviewsCarousel();

    sendGTagViewItem();


    function sendGTagViewItem() {
        let id_product = parseInt($("input[name='id_product']").val()),
            price = $('.product-price').attr('data-price');

        if (!isProduction()) {
            return false;
        }

        gtag('event', 'view_item', {
            'value': $('.product-price').attr('data-price'),
            'currency': woocs_current_currency.name,
            'id': id_product,
            'items': [{
                'id': id_product,
                'item_id': $('.reference').attr('data-ref'),
                'item_name': $('.short-product-info .product-name').text(),
                'price': !parseInt(price) ? 'On Request' : price,
                'currency': woocs_current_currency.name,
                'google_business_vertical': 'retail',
                'item_brand': $('.short-product-info .brand-name').text().trim(),
                'item_category': $(".breadcrumb .breadcrumb-item[data-name]").attr('data-name').trim()
            }]
        });

        /*window.dataLayer.push({
            event: 'view_item',
            value: $('.product-price').attr('data-price'),
            currency: woocs_current_currency.name,
            id: id_product,
            items: [{
                'id': id_product,
                'item_id': $('.reference').attr('data-ref'),
                'item_name': $('.short-product-info .product-name').text(),
                'price': !parseInt(price) ? 'On Request' : price,
                'currency': woocs_current_currency.name,
                'google_business_vertical': 'retail',
                'item_brand': $('.short-product-info .brand-name').text().trim(),
                'item_category': $(".breadcrumb .breadcrumb-item[data-name]").attr('data-name').trim()
            }]
        });*/
    }


    $(document).resize(function () {
        runReviewsCarousel();
    });


    $(document).on('click', '.product-images-box .zoom-icon', null, function () {
        $('#product_images .owl-item.active .image').trigger('click');
    });

    /***
     * Image changing
     */
    $(document).on('click', '.product-images-box .image-switcher .oper', null, function () {
        if ($(this).hasClass('next')) {
            $('.product-images-box .owl-next').trigger('click');
        } else {
            $('.product-images-box .owl-prev').trigger('click');
        }
    });

    $('.short-description .show-more').click(function () {
        $("html, body").animate({
            scrollTop: $("#full_description").offset().top - 130
        }, 1500);
    });


    /**
     * Check and redirect to price suggestion form
     */
    $('.suggest_price').click(function (e) {
        let id_user = parseInt($('#id_current_user').val()),
            id_product = $(this).attr('data-product_id');

        e.preventDefault();

        $(this).addClass('active');

        if (!id_user) {
            //After logging the user will came back to cart product
            window.location.href = site_home_url + '/price-suggestion?id_product=' + id_product;
        } else {
            checkPriceSuggestionRequest(id_product);
        }
    });

    $(document).on('click', '.close-modal', null, function () {
        $('#already-suggested-modal').modal('hide');
    });


    function checkPriceSuggestionRequest(id_product) {
        let url = ajaxurl + '?action=check_suggestion_req&id_product=' + id_product;

        $.get(url, function (data) {

            $('button.suggest_price').prop('disabled', false);
            $('#already-suggested-modal').remove();

            //if request wasn't added before, then redirect to page of creation an offer
            if (data.status === 'success') {
                window.location.href = site_home_url + '/price-suggestion?id_product=' + id_product;
            } else {
                $('body').append(data.message);
                $('#already-suggested-modal').modal();
            }

            $('.suggest_price').removeClass('active');
        });
    }

    const magnificPopupGalleryConfig = {
    fixedContentPos: false,
    overflowY: 'auto',
    midClick: true,
    type: 'image',
    tLoading: 'Loading image #%curr%...',
    preloader: true,
    mainClass: 'mfp-img-mobile',
    gallery: {
        enabled: true,
        navigateByImgClick: true,
        preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
    },
    image: {
        tError: '<a href="%url%">The image could not be loaded.',
        titleSrc: function (item) {
            //return //item.el.attr('title');
            var $gallery = $('#product_images');
            var $result = '';
            var listLen = $gallery.find('.owl-item').length;
            if (listLen > 0) {
                $result = '<div class="mfp-pager">' +
                    '<div class="dots">' +
                    `<ul class="dots${listLen > 8 ? ' scroll' : ''}">`;
                for (var i = 0; i < listLen; i++) {
                    var $cl_active = '';
                    if ((item.index) == i) $cl_active = ' class="active"'; else $cl_active = '';
                    var $thumb = $gallery.find('.owl-item:eq(' + i + ')').find('a').attr('href');
                    $result += '<li' + $cl_active + '>' +
                        '<button type="button" onclick="javascript:$(\'#product_images .owl-item\').magnificPopup(\'goTo\', ' + i + ');return false;"><img src="' + $thumb + '" width="50"></button>' +
                        '</li>';
                }
                $result += '</ul>' +
                    '</div>' +
                    '</div>';
            }
            return $result;
        }
    }
}

    $('.image-popup-gallery-item').magnificPopup(magnificPopupGalleryConfig);

    var magnificPopupGalleryConfig2 = {
    type: 'image',
    fixedContentPos: false,
    fixedBgPos: true,
    overflowY: 'auto',
    closeBtnInside: true,
    preloader: true,
    midClick: true,
    removalDelay: 100,
    mainClass: 'my-mfp-slide-bottom',
    gallery: {
        enabled: true
    }
};

    $('#product_offers .product-offer').each(function () {
        let image = $(this).find('.image');

        if (image.length) {
            image.magnificPopup(magnificPopupGalleryConfig2);
        }
    });


//Prevent showing the image, before zoom plugin will be loaded
$('.image-popup-gallery-item').ready(function () {
    $('.image-popup-gallery-item').each(function () {
        let image = $(this);
        image.attr('href', image.attr('data-url'));
        image.attr('data-url', '');
    });
});


/**
 * Show/Hide "Already Requested" Pop-up.
 */
$(document).on('click', '.already_requested', function () {
    $('#requested_popup1').fadeIn(150);
});

$(document).on('click', '.close_requested', null, function () {
    $('#requested_popup1').fadeOut(150);
});

$(document).on('click', '#outstock_modal img.close-modal, #outstock_modal .cancel', null, function (e) {

    e.preventDefault();

    $('#outstock_modal').fadeOut(150);
});


$(document).on('click', '.part-exchange', null, function (e) {
    let id_product = $(this).attr('data-product_id'),
        url = site_home_url;

    e.preventDefault();

    url += isUserLoggin()
        ? "/about-watch/?product_id=" + id_product
        : "/my-account/?user_login=1&redirect_to=" + escape("/about-watch?product_id=" + id_product);

    window.location.href = url;
});


/**
 * Show sizes list
 */
$(document).on('click', '.size-info .size-list', null, function (e) {
    let sizes = $('#sizes_list');

    if (!$(this).hasClass('active')) {
        $(this).addClass('active');
        sizes.slideDown({
            complete: function () {
                $('#sizes_list').addClass('border-gray')
                $('.size-list').addClass('border-gray');
            }
        });
    } else {
        sizes.slideUp({
            complete: function () {
                $('#sizes_list, .size-list').removeClass('border-gray');
            }
        });
        $(this).removeClass('active');
    }
});

/**
 * Select size(or another selectabel attribute) of product
 */
$(document).on('click', '#sizes_list .size', null, function () {
    let products_ids = jQuery.parseJSON($(this).attr('data-posts'));

    if (!products_ids.length) {
        console.error('Posts for this size are absent');
        return true;
    }

    $('#ref_extension').html($(this).attr('data-ref'));

    $('#sizes_list .size').removeClass('active');
    $(this).addClass('active');

    $('.size-list .selected')
        .attr('data-placeholder', '')
        .text('Size ' + $(this).html().trim());

    $('.short-product-info .product-price').html($(this).attr('data-price'));

    $('.short-product-info .add_to_cart_button')
        .attr('data-id', 'cart_button_' + products_ids[0])
        .attr('data-product_id', products_ids[0]);


    //Set maximum allowed count of products, according selected size
    let qty_field = $('#quantity_items');

    qty_field.find("option").show();
    qty_field.val(1);
    qty_field.find("option:nth-child(n+" + (parseInt($(this).attr('data-count')) + 2) + ")").hide();
});


$(document).on('change', '#quantity_items', null, function () {
    $('.product-oper-box .add_to_cart_button')
        .attr('data-quantity', $(this).val());
});


$(document).on('click', '.buy-button-box .add_to_cart_button', null, function () {
    let handle = $(this),
        product = $('.short-product-info'),
        product_price = product.find('.product-price').length
            ? product.find('.product-price').html().trim()
            : handle.closest('.product-offer').attr('data-price');

    $('.size-list').removeClass('error');

    if (hasRequiredAttributes() || $(this).hasClass('active')) {
        return true;
    }

    $('.size-error').fadeOut(150);

    product_price = !parseInt(product_price) ? 'On Request' : product_price;

    if (isProduction()) {
        gtag('event', 'add_to_cart', {
            'value': product_price,
            'currency': woocs_current_currency.name,
            'items': [{
                item_id: product.find('.reference').attr('data-ref'),
                item_name: product.find('.product-name').text().trim(),
                price: product_price,
                currency: woocs_current_currency.name,
                quantity: 1
            }]
        });

        gtag('event', 'conversion', {
            'send_to': 'AW-396528138/d57TCMbj4bgCEIqUir0B'
        });
    }


    /**
     * Send the request for checking if product is avaialable in stock.
     * If it available, send the request for adding in cart.
     */
    checkProductStock(handle);
});

function checkProductStock(handle) {
    let product_id = handle.attr('data-product_id'),
        quantity = handle.attr('data-quantity'),
        url = '';

    handle.addClass('active');

    if (isProductInStock(handle)) {

        if (!parseInt(current_wp_user_id)) {
            url = site_home_url + '/my-account/?guest_signin=1&redirect_to=/cart/&';
        } else {
            url = cart_url + '?';
        }

        window.location.href = url + 'add-to-cart=' + product_id + '&quantity=' + quantity;
    }
}

function isProductInStock(product) {
    return parseInt(product.attr('data-in-stock'));
}

/**
 * Check if product has attributes that are necessary to be selected before adding in cart
 */
function hasRequiredAttributes() {
    let sizes = $('#sizes_list');

    if (!sizes.length) {
        return false;
    }

    if (!sizes.find('.size.active').length) {
        $('.size-list').addClass('error');
        $('.size-error').fadeIn(150);
        return true;
    }

    return false;
}


/**
 * Offers' filter events
 */
let isActiveFilterEvent = false;

$(document).on('click', '#offers_filter .section', null, function () {
    let section = $(this).closest('.section');

    if (isActiveFilterEvent) {
        return false;
    }

    isActiveFilterEvent = true;

    if (!section.hasClass('active')) {
        closeOffersFilter();
        section.addClass('active');
    } else {
        closeOffersFilter();
    }

    isActiveFilterEvent = false;
});

$(document).click(function (e) {
    let obj = $(e.target);

    if (
        obj.hasClass("item")
        || obj.hasClass("filter-section")
        || obj.hasClass("section-name")
        || obj.hasClass("arrow")
        || obj.hasClass("selected")
    ) {
        return true;
    }

    closeOffersFilter();
});

function closeOffersFilter() {
    $('#offers_filter .section').removeClass('active');
}


$(document).on('click', '#offers_filter .section .item', null, function () {
    let item = $(this).attr('data-item'),
        section = $(this).closest('.section'),
        item_type = section.attr('data-type');


    if (typeof item !== 'undefined') {
        if ('box' === item_type || 'papers' === item_type) {
            item_type = item.indexOf('Original') !== -1 ? 'Yes' : 'No';
        } else {
            item_type = $(this).text();
        }
    } else {
        item = '-1';
    }

    section.find('.section-name').html(__(item_type));
    section.attr('data-selected', item);

    showFilteredOffers();

    //show all hiden offers if user decided to use the filter
    $('#product_offers .product-offer').removeClass('d-none');
});

function showFilteredOffers() {
    let selected_items = getSelectedOffersFillter(),
        offers = $('.product-offer').toArray();

    for (index in offers) {
        let offer = $(offers[index]);

        if (isOfferAvailable(offer, selected_items)) {
            offer.show();
            showHideFiltersAttributes(offer, 'show');
        } else {
            offer.hide();
            showHideFiltersAttributes(offer, 'hide');
        }
    }
}

/**
 * Hide/Show section's items that was included in selected
 *
 * @param {*} offer
 * @param {*} mode
 */
function showHideFiltersAttributes(offer, mode) {
    $('#offers_filter .section').each(function () {
        let type = $(this).attr('data-type'),
            offer_attribute = offer.attr('data-' + type),
            item = $(this).find('.item[data-item="' + offer_attribute + '"]');

        if ('price' === type) {
            offer_attribute = offer_attribute.replaceAll('_', ' ');
        }

        if ('hide' === mode && !hasAvailableOffer(type, offer_attribute)) {
            item.hide();
        } else {
            item.show();
        }
    });
}

function hasAvailableOffer(type, offer_attribute) {
    let offers = $('#product_offers').find(".product-offer[data-" + type + "='" + offer_attribute + "']").toArray(),
        isActive = false;

    for (index in offers) {
        let offer = $(offers[index]);

        if (offer.css('display') !== 'none') {
            isActive = true;
            break;
        }
    }

    return isActive;
}

function getSelectedOffersFillter() {
    let items = {},
        sections = $('#offers_filter').find('.section').toArray();

    for (index in sections) {
        let item = $(sections[index]),
            section_name = item.attr('data-type'),
            section_value = item.attr('data-selected');

        if (typeof section_value === 'undefined' || parseInt(section_value) === -1) {
            continue;
        }

        items[section_name] = section_value;
    }

    return items;
}

function isOfferAvailable(offer, selected_items) {
    let countAvailable = 0;

    for (section_name in selected_items) {
        let offer_attr = offer.attr('data-' + section_name);

        if ('price' === section_name) {
            if ('Price on request' !== offer_attr) {
                offer_attr = parseInt(offer_attr);
                selected_items[section_name] = parseInt(selected_items[section_name]);
            }
        }

        if (typeof offer_attr !== 'undefined' && offer_attr === selected_items[section_name]) {
            countAvailable++;
        }
    }

    return (countAvailable === getSizeObj(selected_items));
}

function getSizeObj(obj) {
    let count = 0;
    for (index in obj) {
        count++;
    }

    return count;
}


/**
 * Show offer's filter(mob version)
 */
$(document).on('click', '#offers_filter_btn', null, function () {
    $('#offers_filter').removeClass('d-flex').addClass('active');
});


$(document).on('click', '#offers_filter .close-filter', null, function () {
    $('#offers_filter').removeClass('active');
});


/**
 * Trucate breadcrumbs if al of them will be outside
 */
setTimeout(function () {
    trucateProductBreadcrumbs();
}, 500);


$(window).on('resize', function () {
    trucateProductBreadcrumbs();
});

function trucateProductBreadcrumbs() {
    let items_width = getBreadItemsWidth(),
        breadcrumbs = $('.breadcrumb-wrp .breadcrumb'),
        show_more = breadcrumbs.find('li.show-more'),
        rest_items = breadcrumbs.find("li:nth-child(n+3):not(:last-child)"),
        doc_width = $(document).width();

    if ((items_width < doc_width - 40) || doc_width >= 1024) {
        breadcrumbs.css('width', '100%').removeClass('truncated');
        rest_items.show();
        show_more.hide();
        return false;
    }

    breadcrumbs
        .css('width', items_width + 'px')
        .addClass('truncated');

    rest_items.hide();

    show_more.show();
}

function getBreadItemsWidth() {
    let items = $('.breadcrumb-wrp .breadcrumb .breadcrumb-item').toArray(),
        total = 0;

    for (index in items) {
        total += $(items[index]).outerWidth() + 10;
    }

    return total;
}

$(document).on('click', '.breadcrumb-wrp .breadcrumb li.show-more', null, function (e) {
    let breadcrumbs = $('.breadcrumb-wrp .breadcrumb');

    e.preventDefault();

    breadcrumbs.css('width', '100%').removeClass('truncated');

    breadcrumbs.find('li:not(.show-more)').show();
    breadcrumbs.find('li.show-more').hide();
});


/**
 * Preload the related products
 */
$.get(ajaxurl + '?action=preload_related_products&product_id=' + $("#product_id").val(), function (data) {
    $('#related_products').html(data);

    runProductsCarousel($(".related-products .products"));
});

/**
 * Preload the customers reviews
 */
$.get(ajaxurl + '?action=load_customers_reviews', function (data) {
    const parent = $('.single-page #trust_reviews');

    if (parent.hasClass('owl-carousel')) {
        parent.owlCarousel('destroy');
    }
    ;

    parent.html(data.data);

    runReviewsCarousel();
});


/**
 * Sold out modal operations
 */
$(document).on('click', '#sold_modal .close', null, function () {
    $('#sold_modal').fadeOut(150);
});


$("#request_sold_product").validate({
    rules: {
        email: {
            email: true,
        },
        first_name: {
            required: true
        },
        customer_phone: {
            startWithoutZero: true,
            Customeminlength: function (element) {
                getCountryCode(element);
                return [6, 'Phone Number'];
            },
            Customemaxlength: function (element) {
                getCountryCode(element);
                return [16, 'Phone Number'];
            }
        }
    },
    messages: {
        email: __('Enter a valid email'),
        customer_phone: {
            Customeminlength: __('Phone number should be minimum of 6 Characters long'),
            Customemaxlength: __('Phone number should not be maximum of 15 Characters long')
        }
    },
    submitHandler: function (form) {
        $("#request_sold_product").find("button[type='submit']").addClass('loading');

        sendSoldOutRequest($(form));
    }
});


function sendSoldOutRequest(form) {

    // console.log(ajaxurl + "?action=send_soldout_request");

    $.post(ajaxurl + "?action=send_soldout_request", form.serialize(), function (data) {
        let result = $('#sold_modal .result');

        form.find("button[type='submit']").removeClass('loading');
        form.css('opacity', '0');

        result.find('.description').html(data.message);
        result.addClass((data.status === 'error') ? 'text-danger' : 'text-success');
        result.show();
    });

}

$(document).on('submit', "#request_sold_product", null, function (e) {
    var isValid = $("#request_sold_product").valid();

    if (isValid) {
        e.preventDefault();
    }
});


$("#request_sold_product input[name='customer_phone']").intlTelInput({
    initialCountry: 'gb',
    separateDialCode: true,
    preferredCountries: ['gb', 'fr', 'us']
});

$(document).on('countrychange', "#request_sold_product input[name='customer_phone']", null, function (event) {
    let form = $(this).closest('form'),
        code = form.find('.selected-flag .selected-dial-code').text(),
        phone = ($(this).val()).replace(code, '');

    let input = $("#request_sold_product input[name='customer_phone']"),
        padding = {
            1: 4,
            2: 4.5,
            3: 5,
            4: 5.5,
            5: 5.7,
            6: 6.5
        };

    input.val(phone).attr('value', phone);
    form.find("input[name='phone_code']").val(code),
        input.attr('style', 'padding-left: ' + padding[code.length] + 'rem !important;');
});

$(document).on('click', '#soldout_show', null, function () {
    let product = $('.short-product-info'),
        modal = $('#sold_modal'),
        ref = product.find('.reference'),
        product_name = product.find('.product-name').html();

    modal.find('.result').hide();
    modal.find('form').css('opacity', 1);
    modal.find("input[name='requested_product']").val($('#product_id').val());
    modal.find('.product_name').html(product_name + "(REF: " + ref.attr('data-ref') + ")");
    modal.fadeIn(150);
});

$('.xs-share-li.digg a').attr('onclick', 'copy_to_Clipboard()');
$('#xs_feed_digg .xs-social-follower-label').text('Copy link');

$('.share_icon_block').hover(
    function () {
        $(this).find('.xs_social_share_widget.custom-class').fadeIn(100);
    },
    function () {
        $(this).find('.xs_social_share_widget.custom-class').fadeOut(100);
    }
);


function copy_to_Clipboard() {
    let dummy = document.createElement('input'),
        text = window.location.href,
        modal = $('#link_copied');

    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand('copy');
    document.body.removeChild(dummy);

    modal.fadeIn(150);
    setTimeout(() => {
        modal.fadeOut(150);
    }, 2000);
}


$(document).on('click', '#unsubscribe-modal .close', null, function () {
    $('#unsubscribe-modal').fadeOut(150);
});


/**
 * Price requesting modal
 */

$(".single-product .request_product").on('click', function (e) {

    e.preventDefault();
    e.stopPropagation();

    let btn = $(this),
        productID = btn.attr('data-product_id'),
        user_id = parseInt($('#id_current_user').val());

    btn.prop('disabled', true);
    btn.addClass('loading clicked-btn');

    if (user_id === 0) {
        showPriceRequestModal(productID, btn);
    } else if (isProfileHasAllData()) {
        sendPriceRequest(productID, user_id);
    } else {
        showPriceRequestModal(productID, btn);
    }
});

function showPriceRequestModal(productID, btn) {
    btn.prop('disabled', false);
    btn.removeClass('loading');

    $('#price_request_modal').find('.requested_product').val(productID);
    $('#price_request_modal').fadeIn(150);

    resizePriceRequestForm();
    showHideDarkLayer();
}


/**
 * Check if profile has all necessary data for creaing price request
 */
function isProfileHasAllData() {

    // console.log('isProfileHasAllData()')

    let form_fields = $("#request_price_product .form-control[required]").toArray(),
        isFormFilled = true;

    for (index in form_fields) {
        let field = $(form_fields[index]).val();

        if (field.trim() === '') {
            isFormFilled = false;
            break;
        }
    }

    return isFormFilled && parseInt($('#is_filled_profile').val());
}

function sendPriceRequest(productID, userID) {
    // console.log('sendPriceRequest() execution');

    let formData = new FormData();

    if (isProduction()) {
        gtag('event', 'conversion', {
            'send_to': 'AW-396528138/1leZCOrBn8wDEIqUir0B'
        });
    }

    formData.append('productId', productID);
    formData.append('userId', userID);
    formData.append('shipping_price', $(".country_shipping_rate").val());

    $.ajax({
        url: site_home_url + "/wp-json/order/requestorder",
        type: 'POST',
        dataType: 'json',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {

            $('.ww_loader_div').removeClass('active_div');

            if (data.status === true) {
                window.location.href = site_home_url + '/request-thank-you/?id=' + data.requestID;
            } else {
                // console.log('data.status === false' );
                $('.single_page_request_btn').html(data.message);
                $('.already_requested').trigger('click');
            }
        }
    });
}

$("#request_price_product").validate({
    ignore: "",
    rules: {
        first_name: {
            multispace: true,
            Customeminlength: [3, 'First name'],
            Customemaxlength: [50, 'First name']
        },

        customer_phone: {
            startWithoutZero: true,
            Customeminlength: function (element) {
                getCountryCode(element);
                return [6, 'Phone Number'];
            },
            Customemaxlength: function (element) {
                getCountryCode(element);
                return [16, 'Phone Number'];
            }
        },
        username: {
            email: true,
            multispace: true,
            remote: site_home_url + '/wp-json/user/checkemailexist',
            Customeminlength: [8, 'Email Address'],
            Customemaxlength: [50, 'Email Address'],
        }
    },
    messages: {
        first_name: {
            multispace: __('Last name should not have multiple spaces'),
        },
        username: {
            remote: __('This email already exist'),
            multispace: __('Email should not have multiple spaces'),
        },
        customer_phone: {
            Customeminlength: __('Phone number should be minimum of 6 Characters long'),
            Customemaxlength: __('Phone number should not be maximum of 15 Characters long'),
            multispace: __('Phone Number should not have multiple spaces'),
        }
    },

    submitHandler: function (form) {
        // console.log('submitHandler');
        let phone = $(form).find("input[name='customer_phone']"),
            code = getCountryCode(phone);

        $("#request_price_product")
            .find("button[type='submit']")
            .addClass('loading');

        $(form).find("input[name='country_phone_code']").val(code.replace('+', ''));

        phone.val(phone.val().replaceAll(code, ''));
        saveUserData($(form));
    }
}); // end validate request_price_product


function saveUserData(form) {

    console.log('saveUserData()');
    console.log(form)

    let formData = new FormData(),
        user_name = (form.find('#first_name').val().trim()).split(' ');

    formData.append('action', 'save_user_data');
    formData.append('billing_email', form.find('#username').val());
    formData.append('email', form.find('#username').val()); // in form the name=username :)
    formData.append('billing_phone', form.find('#customer_phone').val());
    formData.append('billing_phone_code', form.find('#country_phone_code').val());
    formData.append('billing_country', form.find('#user_country').val());
    formData.append('first_name', user_name[0]);
    formData.append('billing_first_name', user_name[0]);
    formData.append('price_request', "1");

    console.log(form.find('#user_country').val());

    if (typeof user_name[1] !== 'undefined') {
        formData.append('last_name', user_name[1]);
        formData.append('billing_last_name', user_name[1]);
    } else {
        formData.append('last_name', user_name[0]);
        formData.append('billing_last_name', user_name[0]);
    }

    $.ajax({
        type: 'POST',
        url: ajaxurl,
        dataType: "json",
        processData: false,
        contentType: false,
        data: formData,
        success: function (data) {
            let product_id = form.find('.requested_product').val(),
                error_message = null;

            console.log('Success Ajax: ');
            console.log(data);

            if ('user_created' === data.status) {
                $('#is_filled_profile').val(1);
                $('#id_current_user').val(data.user_id);
                current_wp_user_id = parseInt(data.user_id);

                $(".request_product.clicked-btn[data-product_id='" + product_id + "']")
                    .prop('disabled', false)
                    // .trigger('click');
            } else {

                $("#price_request_modal button[type='submit']").removeClass('loading');

                error_message = prepareErrorMessage(data);

                if (error_message !== '') {
                    $('#common_error .description').html(error_message);
                    $('#common_error').fadeIn(150);
                }

            }
        },
        error: function (request, status, error) {
            console.log(request);
            console.log(status);
            console.log(error);
        }
    });

}

function prepareErrorMessage(data) {
    let message = '';


    if (typeof data.message !== 'undefined' && data.message !== '') {
        return data.message;
    }

    if (typeof data.errors !== 'undefined') {

        for (index in data.errors) {
            let error = data.errors[index];

            if (typeof error[0] !== 'undefined') {
                message += __(error[0].replaceAll('username', 'email')) + '<br>';
            }
        }
    }


    return message;
}

$(document).on('submit', "#request_price_product", null, function (e) {
    var isValid = $("#request_price_product").valid();

    if (isValid) {
        e.preventDefault();
    }
});

$("#request_price_product input[name='customer_phone']").intlTelInput({
    initialCountry: 'gb',
    separateDialCode: true,
    preferredCountries: ['gb', 'fr', 'us']
});

$(document).on('countrychange', "#request_price_product input[name='customer_phone']", null, function (event) {
    let form = $(this).closest('form'),
        code = form.find('.selected-flag .selected-dial-code').text(),
        phone = ($(this).val()).replace(code, '');

    let input = $("#request_price_product input[name='customer_phone']"),
        padding = {
            1: 4,
            2: 4.5,
            3: 5,
            4: 5.5,
            5: 5.7,
            6: 6.5
        };

    input.val(phone).attr('value', phone);
    form.find("input[name='phone_code']").val(code),
        input.attr('style', 'padding-left: ' + padding[code.length] + 'rem !important;');
});

$(document).on('click', '#price_request_modal .close', null, function () {
    $('#price_request_modal').fadeOut(150);
    $('.request_product').prop('disabled', false);
    showHideDarkLayer('hide');
});


$(document).on('blur change keyup', '#price_request_modal .form-control', null, function () {
    let handle = $(this),
        field_box = handle.closest('.form-group');

    if (handle.hasClass('valid')) {
        if (!field_box.find('.is-valid').length) {
            field_box.append("<div class='is-valid'></div>");
        }
    } else {
        field_box.find('.is-valid').remove();
    }
});

/**
 * Disable possibility to send request if user doesn't want to create an account
 */
$(document).on('click', '#create_account_consigment', null, function () {
    $("#price_request_modal button[type='submit']")
        .prop('disabled', !$(this).prop('checked') ? true : false);
});

$(window).resize(function () {
    resizePriceRequestForm();
});

function resizePriceRequestForm() {
    let modal = $('#price_request_modal');

    if (!modal.find('.auth-buttons-box').length) {
        modal.css('height', $(window).height() < 600 ? '96%' : 'auto');
    }
}

$(document).on('click', ".xs-login__item.wslu-color-scheme--ww", null, function (e) {
    let productID = $("#price_request_modal .requested_product").val(),
        url = site_home_url + '/my-account?reqProduct=1&requestproduct=' + productID + '&redirect_to=' + encodeURI('/request-thank-you/?requested_product_id=' + productID);

    e.preventDefault();

    window.location.href = url;
});
$(document).on('change', '#user_country', null, function () {
    // console.log($(this).val());

    if ($(this).val() !== '') {
        $('#user_country-error').hide();
    } else {
        $(this).closest('.field-box').find('.is-valid').remove();
    }
});

});// end ready wrapp