$(function() {
    var basket = new ArtboxBasket({
        'cartSelector': '#cart'
    });
    /**
     * Modal form submit code
     */
    $(document)
        .on('beforeSubmit', '#feedback-form', function(e) {
            var f = this;
            var form = $(this);
            var formData = form.serialize();
            $.ajax({
                url: form.attr("action"),
                type: form.attr("method"),
                data: formData,
                success: function(data) {
                    f.reset();
                    $('#feedback-modal')
                        .modal('hide');
                    $('#success-modal')
                        .modal('show');
                },
                error: function() {
                    $('#feedback-modal')
                        .modal('hide');
                }
            });
        })
        .on('submit', '#feedback-form', function(e) {
            e.preventDefault();
        });
    /**
     * Contact form submitting
     */
    $(document)
        .on('beforeSubmit', '#contact-form', function(e) {
            var f = this;
            var form = $(this);
            var formData = form.serialize();
            $.ajax({
                url: form.attr("action"),
                type: form.attr("method"),
                data: formData,
                success: function(data) {
                    f.reset();
                    form.replaceWith(data.alert);
                },
                error: function() {
                }
            });
        })
        .on('submit', '#contact-form', function(e) {
            e.preventDefault();
        });
    /**
     * Button UP code
     */
    if ($('#back-to-top').length) {
        var scrollTrigger = 100, // px
            backToTop = function() {
                var scrollTop = $(window)
                    .scrollTop();
                if (scrollTop > scrollTrigger) {
                    $('#back-to-top')
                        .addClass('show');
                } else {
                    $('#back-to-top')
                        .removeClass('show');
                }
            };
        backToTop();
        $(window)
            .on('scroll', function() {
                backToTop();
            });
        $('#back-to-top')
            .on('click', function(e) {
                e.preventDefault();
                $('html,body')
                    .animate({
                        scrollTop: 0
                    }, 700);
            });
    }
    $(document)
        .on('click', '.add-to-basket', function(e) {
            e.preventDefault();
            var id = $(this)
                .data('id');
            var xhr = basket.add(id, 1);
            xhr.done(function() {
                $.pjax.reload({
                    container: '#basket-modal',
                    fragment: '#basket-modal',
                    timeout: 5000
                });
            });
            if ($('.alert-cart').length > 0) {
            } else {
                $('body')
                    .prepend($("
Товар добавлен в корзину.
"));
                setTimeout(function() {
                    $(".alert-cart")
                        .addClass("active");
                }, 100);
                setTimeout(function() {
                    $(".alert-cart")
                        .removeClass("active");
                }, 3500);
                setTimeout(function() {
                    $(".alert-cart")
                        .remove();
                }, 3600);
            }
        });
    $(document)
        .on('click', '.remove-product-cart', function(e) {
            e.preventDefault();
            var id = $(this)
                .parents('.product-row-basket')
                .data('id');
            showLoader('#basket');
            showLoader('#basket-modal');
            var xhr = basket.remove(id);
            xhr.done(function() {
                if ($('#basket').length) {
                    $.pjax.reload({
                        container: '#basket',
                        fragment: '#basket',
                        timeout: 5000,
                        async: false
                    });
                }
                $.pjax.reload({
                    container: '#basket-modal',
                    fragment: '#basket-modal',
                    timeout: 5000,
                    async: false
                });
            })
        });
    $(document)
        .on('change', '.increase-product-basket', function(e) {
            var id = $(this)
                .parents('.product-row-basket')
                .data('id');
            showLoader('#basket');
            showLoader('#basket-modal');
            var xhr = basket.set(id, $(this)
                .val());
            xhr.done(function() {
                if ($('#basket').length) {
                    $.pjax.reload({
                        container: '#basket',
                        fragment: '#basket',
                        timeout: 5000,
                        async: false
                    });
                }
                $.pjax.reload({
                    container: '#basket-modal',
                    fragment: '#basket-modal',
                    timeout: 5000,
                    async: false
                });
            });
        });
    $(document)
        .on('click', 'li.disabled a', function(e) {
            e.preventDefault();
        });
    $(document)
        .on('submit', '#fast-buy-form', function(e) {
            e.preventDefault();
        });
    $(document)
        .on('afterValidate', '#fast-buy-form', function(e, m, errors) {
            if (!errors.length) {
                var form = $(e.target);
                var action = form.attr('action');
                $.post(action, form.serialize(), function(data) {
                    if (data.success) {
                        $('#oneclick-modal')
                            .find('.modal-body')
                            .text(data.msg);
                    }
                });
            }
        }.bind(this));
    $(document)
        .on('click', '.wishlist-rm, .wishlist-add', function() {
            var button = $(this);
            $.ajax({
                url: button.data('url'),
                type: "POST",
                data: {
                    'variant': button.data('variant'),
                    'product': button.data('product'),
                    'user': button.data('user')
                },
                success: function(data) {
                    button.replaceWith(data.button);
                    new PNotify({
                        title: 'Info',
                        text: data.message,
                        type: 'info',
                        styling: 'fontawesome'
                    });
                }
            })
        });
    $(document)
        .on('click', '.wishlist-delete', function(e) {
            e.preventDefault();
            var button = $(this);
            $.ajax({
                url: button.data('url'),
                type: "POST",
                data: {
                    'product': button.data('product'),
                    'variant': button.data('variant'),
                    'user': button.data('user')
                },
                success: function(data) {
                    if (data.success) {
                        $.pjax.reload({container: '#wishlist-products'});
                        new PNotify({
                            title: 'Info',
                            text: data.message,
                            type: 'info',
                            styling: 'fontawesome'
                        });
                    }
                }
            });
        });
    $(document)
        .on('click', '.sort-cat>a', function(e) {
            $(this)
                .parent()
                .toggleClass("active");
            return false;
        });
    $(document)
        .on('click', '.sorter li a', function(e) {
            var sortclick = $(this)
                .text();
            parentsort = $(".sort-cat a span");
            pstext = $(parentsort)
                .text();
            mainlink = $(".sort-cat a")
                .attr('href');
            newmainlink = $(this)
                .attr('href');
            $(parentsort)
                .text(sortclick);
            $(".sort-cat>a")
                .attr('href', newmainlink);
            $(this)
                .text(pstext);
            $(this)
                .attr('href', mainlink);
            $(".sort-cat>a")
                .click();
            $(location)
                .attr('href', newmainlink);
            return false;
        });
    // Price slider
    $('.price-inputs input')
        .keypress(function(key) {
            if (key.charCode < 48 || key.charCode > 57) {
                return false;
            }
        });
    var priceSlider = $(".price_slider input");
    var pricemin = priceSlider.data("pricemin");
    var pricemax = priceSlider.data("pricemax");
    var currentMin = priceSlider.data("currentmin");
    var currentMax = priceSlider.data("currentmax");
    $(".price-inputs #price-min")
        .val(currentMin);
    $(".price-inputs #price-max")
        .val(currentMax);
    $("#price_interval")
        .ionRangeSlider({
            type: "double",
            min: pricemin,
            max: pricemax,
            from: currentMin,
            to: currentMax,
            onChange: function(data) {
                $(".price-inputs #price-min")
                    .val(data.from);
                $(".price-inputs #price-max")
                    .val(data.to);
            }
        });
    var slider = $("#price_interval")
        .data("ionRangeSlider");
    $(document)
        .on('change', '.price-inputs #price-min', function() {
            var newmin = $(this)
                .val();
            currentmax = $(".price-inputs #price-max")
                .val();
            if (newmin > currentmax) {
                newmin = currentmax;
                $('.price-inputs #price-min')
                    .val(currentmax);
            } else if (newmin > pricemax) {
                newmin = pricemax;
                $('.price-inputs #price-min')
                    .val(pricemax);
            }
            slider.update({from: newmin});
        });
    $(document)
        .on('change', '.price-inputs #price-max', function() {
            var newmax = $(this)
                .val();
            currentmin = $(".price-inputs #price-min")
                .val();
            if (newmax < currentmin) {
                newmax = currentmin;
                $('.price-inputs #price-max')
                    .val(currentmin);
            } else if (newmax > pricemax) {
                newmax = pricemax;
                $('.price-inputs #price-max')
                    .val(pricemax);
            }
            slider.update({to: newmax});
        });
    $(document)
        .on('click', '.price-apply', function() {
            var max = $('#price-max')
                .val();
            var min = $('#price-min')
                .val();
            console.log(max, min);
            var href = window.location.href;
            var question = href.indexOf('?');
            var queryString = '';
            if (question !== -1) {
                queryString = href.substr(question);
                href = href.substr(0, question);
            }
            var count = 0;
            var pos = -1;
            while ((pos = href.indexOf('/', pos + 1)) !== -1) {
                count++;
            }
            if (count === 5) {
                window.location.href = href + '/price-' + min + '-' + max + queryString;
            } else {
                var result = href.match(/\/[^\/]*price-(\d+)-(\d+)$/);
                if (result) {
                    window.location.href = href.replace(/(\/[^\/]*)price-\d+-\d+$/, '$1price-' + min + '-' + max) + queryString;
                }
            }
        });
    // End of price slider
    $('.vcovers')
        .perfectScrollbar({wheelSpeed: 0.5});
    $(document)
        .on('click', '.sidebar-menu .form-group .hiddens-button a.btn', function() {
            $(this)
                .parent()
                .parent()
                .find(".hiddens")
                .toggleClass("active");
            $(this)
                .text(function(i, text) {
                    return text === "Ещё" ? "Скрыть" : "Ещё";
                });
            return false;
        });
    $(document)
        .on('beforeSubmit', '.share-basket-form', function(e) {
            $.post($(this)
                .attr('action'), $(this)
                .serialize(), function(data) {
            });
            new PNotify({
                title: $(this)
                    .data('title'),
                text: $(this)
                    .data('msg'),
                type: 'info',
                styling: 'fontawesome'
            });
            this.reset();
            return false;
        });
    $(document)
        .on('submit', '.share-basket-form', function(e) {
            $.post($(this)
                .attr('action'), $(this)
                .serialize(), function(data) {
            });
            new PNotify({
                title: $(this)
                    .data('title'),
                text: $(this)
                    .data('msg'),
                type: 'info',
                styling: 'fontawesome'
            });
            this.reset();
            return false;
        });
});
function showLoader(container) {
    $(container)
        .prepend('');
}