function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl)
})

function setCookie(name, value, options) {
    options = options || {};

    var expires = options.expires;

    if (typeof expires == "number" && expires) {
        var d = new Date();
        d.setTime(d.getTime() + expires * 1000);
        expires = options.expires = d;
    }
    if (expires && expires.toUTCString) {
        options.expires = expires.toUTCString();
    }

    value = encodeURIComponent(value);

    var updatedCookie = name + "=" + value;

    for (var propName in options) {
        updatedCookie += "; " + propName;
        var propValue = options[propName];
        if (propValue !== true) {
            updatedCookie += "=" + propValue;
        }
    }

    document.cookie = updatedCookie;
}

function set_session_var(param, value, callback) {
    if (param!=undefined) {
        $.post(
            '/api/set_session_var/',
            {param: param, value: value},
            function(r){if(callback!=undefined) {callback();}},
            'json'
        );
    }
}

function set_session_arr(params, callback) {
    if (params!=undefined) {
        $.post(
            '/api/set_session_arr/',
            {params: params},
            function(r){if(callback!=undefined) {callback();}},
            'json'
        );
    }
}

// (123456789.12345).formatMoney(2, '.', ',');
Number.prototype.formatMoney = function(c, d, t){
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 0 : c,
        d = d == undefined ? "," : d,
        t = t == undefined ? " " : t,
        s = n < 0 ? "-" : "",
        i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
        j = (j = i.length) > 3 ? j % 3 : 0;
    if (i.length < 5) {
        return s + i;
    }
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
var RUB_SYMB = '&nbsp;₽';


///////////////////////////////////////
// CSRF
///////////////////////////////////////
var csrftoken = getCookie('_jo_csrf');
function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});


///////////////////////////////////////
// Cart functions
///////////////////////////////////////
var cart = {
    add: function (pk, quantity, callback) {
        quantity = quantity || 1
        return $.post(URLS.addItem, {pk: pk, quantity: quantity}, 'json').done(callback);
    },
    remove: function (itemPK, callback) {
        return $.post(URLS.removeItem, {pk: itemPK}, 'json').done(callback);
    },
    changeQuantity: function (pk, quantity, callback) {
        return $.post(URLS.changeQuantity, {pk: pk, quantity: quantity}, 'json').done(function() {cart.updateWidget(); callback();})
    },
    empty: function () {
        $.post(URLS.emptyCart, 'json')
    },
    updateWidget: function() {
        $('.cart-widget').load('/cart/cart-widget/');
    },
};

function send_feedback(email, source, phone, name, comment, $loader, callback) {
    if(!phone){
        $.alert({
            title:'',
            useBootstrap:false,
            boxWidth:'300px',
            theme:'jo',
            animateFromElement:false,
            content:'Укажите телефон',
            buttons: {
                'ok': {
                    text: 'Понял',
                    btnClass: 'btn-center-muted',
                }
            }
        });
        if ($loader != undefined) {
            $loader.remove();
        }
        return false;
    } else {
        $.post(
            '/api/feedback/',
            {
                name:name,
                phone:phone,
                comment:comment,
                email:email,
                source:source
            }
        ).done(function() {
            $.alert({
                title:'Спасибо!',
                titleClass:'sm',
                useBootstrap:false,
                boxWidth:'300px',
                theme:'jo',
                animateFromElement:false,
                content:'Скоро с вами свяжутся.',
                buttons: {
                    'ok': {
                        text: 'Закрыть',
                        btnClass: 'btn-center-muted',
                    }
                }
            });
            if (callback != undefined) {
                callback();
            }
            if ($loader != undefined) {
                $loader.remove();
            }
        });
    }
}

const COMMA_CHAR_HEX_LENGTH = 3;
const GA_CUSTOM_DIMENSION_MAX_LENGTH = 150;

function getArrayIndicesForSplitByMaxLength(
        array, maxLength, getItemLen = arrayItem => 1, joiningLength = 0, returnSlices = false) {
    // returns indices to split array into smaller arrays each of which is shorter than maxLength.
    // getItemLen - returns length for single array item
    // joiningLength - additional length to add between items
    // returnSlices - instead returns slices = [[beg, end], ...]
    // examples:
    //   f([1, 2, 3, 4, 5], 2) -> [2, 3]
    //   f(['aa', 'bb', 'ccc', 'dd'], 5, _ => _.length, 1) -> [2, 3] -> [['aa', 'bb'], ['ccc'], ['dd']] ->
    //      'aa bb', 'ccc', 'dd'
    let splitIndices = [];
    let extractingIndicesCallback = (previousLength, arrayItem, crntIdx) => {
        let itemLength = getItemLen(arrayItem);
        let currentLength = previousLength + itemLength;
        if (crntIdx > 0) {
            currentLength += joiningLength;
        }

        if (currentLength > maxLength) {
            splitIndices.push(crntIdx);
            currentLength = itemLength;
        }

        return currentLength;
    };

    array.reduce(extractingIndicesCallback, 0);

    if (returnSlices === false){
        return splitIndices;
    } else {
        splitIndices = [0].concat(splitIndices);
        splitIndices.push(array.length);

        let slices = splitIndices.map((elem, idx) => [elem, splitIndices[idx + 1]]);
        slices.pop();  // remove (length, undefined)

        return slices;
    }
}

(function() {
    /////////////////////////////////
    // Call request
    $('.request-call').click(function(e) {
        e.preventDefault();
        var box_width = '413px';
        var window_width = $(window).width();
        if (window_width < 1000) {
            box_width='100%';
        }
        $.confirm({
            title: '<span class="icon ion-md-phone-portrait"></span>&nbsp;Обратный звонок',
            backgroundDismiss: true,
            theme:'jo big',
            useBootstrap: false,
            draggable: false,
            content: '' +
            '<form action="" class="form-vertical">' +
            '<div class="form-group"><input type="text" placeholder="Ваше имя" class="name form-control" required /></div>' +
            '<div class="form-group"><input type="text" placeholder="Номер телефона" class="phone form-control" required /></div>' +
            '<div class="form-group" style="padding-top:15px;opacity:0.5;font-style:italic;font-size:12px;">Заказывая обратный звонок, вы&nbsp;даете согласие на&nbsp;обработку персональных данных</div>' +
            '</form>',
            boxWidth: box_width,
            closeIcon: true,
            closeIconClass: 'close-icon',
            buttons: {
                formSubmit: {
                    text: 'Заказать звонок',
                    btnClass: 'btn-primary btn-block',
                    action: function () {
                        var phone = this.$content.find('.phone').val();
                        var name = this.$content.find('.name').val();
                        if(!phone){
                            $.alert({
                                title:'',
                                useBootstrap:false,
                                boxWidth:'300px',
                                theme:'jo',
                                animateFromElement:false,
                                content:'Укажите телефон',
                                buttons: {
                                    'ok': {
                                        text: 'Понял',
                                        btnClass: 'btn-secondary btn-block',
                                    }
                                }
                            });
                            return false;
                        } else {
                            $.post('/api/request_call/', {name:name,phone:phone}).done(function() {
                                $.alert({
                                    title:'Спасибо!',
                                    titleClass:'sm',
                                    useBootstrap:false,
                                    animateFromElement:false,
                                    boxWidth:'300px',
                                    theme:'jo',
                                    content:'Вам скоро перезвонят.',
                                    buttons: {
                                        'ok': {
                                            text: 'Закрыть',
                                            btnClass: 'btn-secondary btn-block',
                                        }
                                    }
                                });
                                ym(25777058, 'reachGoal', 'zvonokshapkat');
                            });
                        }
                    }
                },
            },
            onContentReady: function () {
                // bind to events
                var jc = this;
                this.$content.find('form').on('submit', function (e) {
                    // if the user submits the form by pressing enter in the field.
                    e.preventDefault();
                    jc.$$formSubmit.trigger('click'); // reference the button and click it
                });
            }
        });
    });

    $cart = undefined;
    $(document).on('click', '.add-to-cart', function(e) {
        e.preventDefault();
        var self = $(this);
        if (self.hasClass('disabled')) {
            return;
        }
        var pid = self.data('pid');
        var product_name = self.data('name');
        var article = self.data('article');
        var category = self.data('category');
        var brand = self.data('brand');
        var price = self.data('price');
        var q = self.parent().find('input').val();
        q = q || 1;

        var box_width = '860px';
        var window_width = $(window).width();
        if (window_width < 1000) {
            box_width='100%';
        }

        cart.add(pid, q).done(
            function() {
                var product_obj = {
                    'name': product_name,
                    'id': pid,
                    'price': price,
                    'brand': brand,
                    'category': category,
                    'quantity': 1
                };
                var add_to_cart_layer = {
                    'ecommerce': {
                        'currencyCode': 'RUB',
                        'add': {
                            'products': [product_obj]
                        }
                    }
                }
                dataLayer.push(add_to_cart_layer);
                $.confirm({
                    title: '<span class="icon ion-md-checkmark"></span> Товар добавлен',
                    useBootstrap: false,
                    boxWidth: box_width,
                    draggable: false,
                    content: 'URL:/cart/cart-popup/',
                    backgroundDismiss: 'continue_shopping',
                    closeIcon: true,
                    closeIconClass: 'close-icon',
                    columnClass: 'cart-popup-wrapper',
                    theme:'jo',
                    onContentReady: function () {
                        this.setContentPrepend('<span></span>'); // safari bugfix

                        // update cart widget in header
                        cart.updateWidget();

                        //self.addClass('in-cart');
                        $cart = this;
                        if (self.hasClass('detail')) {
                            self.text('В корзине');
                        }
                    },
                    onDestroy: function() {
                        // bug workaround:
                        $('body').removeClass('jconfirm-no-scroll-'+this._id);
                        // maybe i've misconfigured jconfirm instance,
                        // but it did not return scrolling to 'body' on modal close...
                        // It happens only if ajax response html contains images

                        $cart_popup_content = undefined;
                    },
                    buttons: {
                        goto_cart: {
                            text: '<span class="icon ion-md-cart"></span>&nbsp;Оформить заказ',
                            btnClass: 'float-right btn-primary',
                            keys: ['enter'],
                            action: function(){
                                window.location.href = '/cart/';
                            }
                        },
                        continue_shopping: {
                            text: 'Продолжить покупки',
                            btnClass: 'float-left btn-secondary',
                            keys: ['esc'],
                            action: function() {}
                        },
                    }
                });
            }
        );
    });

    $(document).on('click', '.add-to-compare', function(e) {
        $('.compare-widget .icon').addClass('like');
        e.preventDefault();
        var self = $(this);
        self.removeClass('add-to-compare');
        self.addClass('remove-from-compare active');
        self.attr({'data-original-title': 'Убрать из сравнения'});
        $('.tooltip-inner').text('Убрать из сравнения');
        self.children().css('color', '#d02229');
        $.get('/compare/add/?pid='+self.data('pid'), function(r) {
            $('.compare-widget').load('/personal/compare/get_widget/');
        });
    });

    $(document).on('click', '.remove-from-compare', function(e) {
        e.preventDefault();
        var self = $(this);
        self.removeClass('remove-from-compare active');
        self.addClass('add-to-compare');
        self.attr({'data-original-title': 'Добавить в сравнение'});
        $('.tooltip-inner').text('Добавить в сравнение');
        $.get('/compare/remove/?pid='+self.data('pid'), function(r) {
            $('.compare-widget').load('/personal/compare/get_widget/');
            if(window.location.pathname.indexOf('/compare/') >= 0)
                window.location.reload();
        });
    });

    $(document).on('click', '.add-to-favorites', function(e) {
        $('.favorites-widget .icon').addClass('like');
        e.preventDefault();
        var self = $(this);
        self.addClass('remove-from-favorites');
        self.removeClass('add-to-favorites');
        $.get('/personal/favorites/add/'+self.data('pid')+'/', function(r) {
            $('.favorites-widget').load('/personal/favorites/get_widget/');
            $('.favorites-personal-widget').load('/personal/favorites/get_personal_widget/');
        });

    });

    $(document).on('click', '.remove-from-favorites', function(e) {
        e.preventDefault();
        var self = $(this);
        self.removeClass('remove-from-favorites');
        self.addClass('add-to-favorites');

        $.get('/personal/favorites/remove/'+self.data('pid')+'/', function(r) {
            $('.favorites-widget').load('/personal/favorites/get_widget/');
            $('.favorites-personal-widget').load('/personal/favorites/get_personal_widget/');
            if(window.location.pathname.indexOf('/personal/favorites/') >= 0)
                self.parent().parent().parent().fadeOut();
        });
    });

    
    $(document).on('click', '.remove-from-cart', function(e) {
        e.preventDefault();
        var self = $(this);
        var pid = self.data('pid');
        var product_obj = self.data('product');
        product_obj['quantity'] = self.data('quantity');
        var box_width = '300px';
        var window_width = $(window).width();
        if (window_width < 1000) {
            box_width='200px';
        }
        $.confirm({
            title: '',
            content: 'Подтверждаете удаление из корзины?',
            useBootstrap: false,
            theme:'jo',
            draggable: false,
            boxWidth: box_width,
            backgroundDismiss: 'cancel',
            buttons: {
                confirm: {
                    btnClass: 'float-left btn-secondary btn-sm',
                    text: 'Да',
                    keys: ['enter'],
                    action: function () {
                        cart.remove(pid, update_cart).done(function() {
                            var remove_from_cart_layer = {
                                'ecommerce': {
                                    'currencyCode': 'RUB',
                                    'remove': {
                                        'products': [product_obj]
                                    }
                                }
                            }
                            dataLayer.push(remove_from_cart_layer);
                            cart.updateWidget();
                        });
                        self.parent().parent().slideUp('slow', function() {
                            if (!self.hasClass('is-popup')) {
                                window.location.reload();
                            }
                        });
                    },
                },
                cancel: {
                    text: 'Нет',
                    btnClass: 'float-right btn-primary btn-sm',
                    keys: ['esc'],
                    action: function () {
                        // console.log('Canceled!');
                    }
                }
            }
        });
    });

    // MAKE TIMER!
    function update_cart() {
        if ($cart !== undefined) {
            $cart.showLoading();
        } else {
            $('.cart-overlay').css({'display':'flex'});
        }
        setTimeout(function() {
            if ($cart !== undefined) {
                $cart.$content.load('/cart/cart-popup/', function(response) {
                    $cart.hideLoading();
                });
            } else {
                window.location.reload();
            }
        }, 100);
    };

    var qbutt_debounce_timer,
        qinput_keyup_debounce_timer,
        DEBOUNCE_TIME = 100;

    var incr_cart_item = function(e){
        var self = $(this);
        var $input = self.parent().find('input');
        var pid = $input.data('pid');
        var new_q = parseInt($input.val()) + 1;
        $input.val(new_q);
        if (qbutt_debounce_timer !== undefined) {clearTimeout(qbutt_debounce_timer);}
        qbutt_debounce_timer = setTimeout(function() {
            cart.changeQuantity(pid, new_q, update_cart);
            product_obj = self.parent().data('product');
            product_obj['quantity'] = 1;
            var add_from_cart_layer = {
                'ecommerce': {
                    'currencyCode': 'RUB',
                    'add': {
                        'products': [product_obj]
                    }
                }
            }
            dataLayer.push(add_from_cart_layer);
        }, DEBOUNCE_TIME);
    }

    var decr_cart_item = function(e){
        var self = $(this);
        var $input = self.parent().find('input');
        var pid = $input.data('pid');
        if ($input.val() > 1) {
            var new_q = parseInt($input.val()) - 1;
            $input.val(new_q);
            if (qbutt_debounce_timer !== undefined) {clearTimeout(qbutt_debounce_timer);}
            qbutt_debounce_timer = setTimeout(function() {
                cart.changeQuantity(pid, new_q, update_cart);
                product_obj = self.parent().data('product');
                product_obj['quantity'] = 1;
                var remove_from_cart_layer = {
                    'ecommerce': {
                        'currencyCode': 'RUB',
                        'remove': {
                            'products': [product_obj]
                        }
                    }
                }
                dataLayer.push(remove_from_cart_layer);
            }, DEBOUNCE_TIME);
        }
    }
    $(document).on('click', '.q-control .incr', incr_cart_item);
    $(document).on('click', '.q-control .decr', decr_cart_item);

    $(document).on('input', '.q-control input', function() {
        var $input = $(this);
        var pid = $input.data('pid');
        var new_q = $input.val();
        if (qinput_keyup_debounce_timer !== undefined) {
            clearTimeout(qinput_keyup_debounce_timer);
        }
        if (new_q >= 0) {
            qinput_keyup_debounce_timer = setTimeout(function() {cart.changeQuantity(pid, new_q, update_cart);}, DEBOUNCE_TIME);
        }
    });

    $(document).on('click', '.show-more', function(e) {
        e.preventDefault();
        var $self = $(this);
        var href = $self.attr('href');
        $self.attr('href', '#');
        $self.append('&nbsp;<div class="spinner-grow spinner-grow-sm"></div>');
        $.ajax({
            url:href,
            type:'GET',
        }).done(function(r) {
            $('.products .pagination-container').remove();
            $('.products').append(r);

            let search_re = /\/search\//;
            let pagetype = (search_re.exec(window.location.pathname) != null) ? 'searchresults' : 'category';

            let productArticles = $(r).data('product-articles');
            let slices = getArrayIndicesForSplitByMaxLength(
                productArticles, GA_CUSTOM_DIMENSION_MAX_LENGTH, _ => _.length, COMMA_CHAR_HEX_LENGTH, true);

            for (let i = 0; i < slices.length; i++) {
                dataLayer.push({
                    'event': 'product_list_view',
                    'ecomm_pagetype': pagetype,
                    'ecomm_prodid':productArticles.slice(slices[i][0], slices[i][1])
                });
            }
        });
    });

    // $(document).on('click', '._gtm', function(e) {
    //     var cur_page = $('.pagination.big').first().data('cur-page');
    //     var url_string = window.location.href;
    //     var url = new URL(url_string);
    //     url.searchParams.set('page', cur_page);
    //     url.searchParams.set('scrollto', $(this).parent().parent().attr('id'));
    //     var url_path = window.location.pathname + '?' + url.searchParams.toString();
    //     window.history.pushState(null, null, url_path);

    //     var href = $(this).attr('href');
    //     var article = $(this).data('article');
    //     var obj = undefined;
    //     if (typeof page_objects !== 'undefined') {
    //         obj = page_objects[article];
    //     }
    //     if (obj == undefined) {
    //         obj = $(this).data('product');
    //     }
    //     if (obj == undefined) {
    //         window.location.href = href;
    //     }

    //     var list_name = $(this).data('list-name');
    //     delete obj.list;
    //     var click_layer = {
    //         event: 'item-click',
    //         ecommerce: {
    //             click: {
    //                 actionField: {list: list_name},
    //                 products: [obj]
    //             }
    //         }
    //     }
    //     dataLayer.push(click_layer);
    //     set_session_param('last_viewed_list', list_name, function() {});
    // });

    $('.apply-form').click(function(e) {
        e.preventDefault();
        var $self = $(this);

        var source = $self.data('source');
        var fields = $self.data('fields');
        var form_fields = [
            '<div class="group"><input type="text" placeholder="Ваше имя" class="name form-control" required /></div>',
            '<div class="group"><input type="text" placeholder="Номер телефона" class="phone form-control" required /></div>',
        ]
        if (fields != undefined) {
            fields = fields.split(',');
            for (var i = 0; i<fields.length; i++) {
                if (fields[i] == 'email') {
                    form_fields.push('<div class="group"><input type="text" placeholder="E-mail" class="email form-control" /></div>');
                }
                if (fields[i] == 'comment') {
                    form_fields.push('<div class="group"><input type="text" placeholder="Комментарий" class="comment form-control" /></div>');
                }
            }
        }
        var formtitle = $self.data('formtitle');
        if (formtitle == undefined) {
            return false;
        }
        var box_width = '413px';
        var window_width = $(window).width();
        if (window_width < 1000) {
            box_width='100%';
        }
        $.confirm({
            title: '<span class="emoji bhr lg"></span>&nbsp;' + formtitle,
            backgroundDismiss: true,
            theme:'jo big',
            useBootstrap: false,
            draggable: false,
            content: '' +
            '<form action="" class="basic-form">' + form_fields.join(' ') + '</form>',
            boxWidth: box_width,
            closeIcon: true,
            closeIconClass: 'close-icon',
            buttons: {
                formSubmit: {
                    text: 'Отправить заявку',
                    btnClass: 'btn-red btn-center',
                    action: function () {
                        var phone = this.$content.find('.phone').val();
                        var name = this.$content.find('.name').val();
                        var comment = this.$content.find('.comment').val();
                        var email = this.$content.find('.email').val();
                        return send_feedback(email, source, phone, name, comment);
                    }
                },
            },
            onContentReady: function () {
                // bind to events
                var jc = this;
                this.$content.find('form').on('submit', function (e) {
                    // if the user submits the form by pressing enter in the field.
                    e.preventDefault();
                    jc.$$formSubmit.trigger('click'); // reference the button and click it
                });
            }
        });
    });


    $('.personal-login').click(function(e) {
        e.preventDefault();
        var self = $(this);
        var cmodal = $.confirm({
            animation:'right',
            title: '',
            useBootstrap: false,
            boxWidth: '400px',
            theme:'jo',
            content: 'url:/login/',
            backgroundDismiss: 'cancel',
            closeIcon: true,
            closeIconClass: 'close-icon',
            onContentReady: function () {
                this.setContentPrepend('<span></span>'); // safari bugfix
                this.$content.find('button').remove();

                var $forgot_passw = cmodal.$content.find('.forgot-pass');
                $forgot_passw.click(function(e) {
                    e.preventDefault();

                    cmodal.close();
                    
                    var cmodal_reset_passw = $.confirm({
                        animation:'right',
                        title: '',
                        theme:'jo',
                        useBootstrap: false,
                        boxWidth: '400px',
                        content: 'url:/password_reset/',
                        backgroundDismiss: 'cancel',
                        closeIcon: true,
                        closeIconClass: 'close-icon',
                        onContentReady: function () {
                            this.setContentPrepend('<span></span>'); // safari bugfix
                            this.$content.find('button').remove();
                        },
                        onDestroy: function() {
                            $('body').removeClass('jconfirm-no-scroll-'+this._id);
                        },
                        buttons: {
                            continue: {
                                text: 'Восстановить',
                                btnClass: 'btn btn-primary btn-block btn-lg',
                                keys: ['enter'],
                                action: function() {
                                    var $login = cmodal_reset_passw.$content.find('#id_email');
                                    if ($login.val() != '') {
                                        cmodal_reset_passw.$content.find('.errors').empty();
                                        $.ajax({
                                            type:'POST',
                                            url: '/password_reset/',
                                            data: cmodal_reset_passw.$content.find('form').serialize(),
                                            success: function(response) {
                                                console.log(response);
                                            }
                                        });
                                        return false;
                                    } else {
                                        $.alert({
                                            title:'',
                                            useBootstrap:false,
                                            boxWidth:'300px',
                                            animation:'top',
                                            content:'Укажите номер телефона или e-mail',
                                            buttons: {
                                                'ok': {
                                                    text: 'Понял',
                                                    btnClass: 'btn-popup',
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        }
                    });
                });
            },
            onDestroy: function() {
                // bug workaround:
                $('body').removeClass('jconfirm-no-scroll-'+this._id);
                // maybe i've misconfigured jconfirm instance,
                // but it did not return scrolling to 'body' on modal close...
                // It happens only if ajax response html contains images
            },
            buttons: {
                continue: {
                    text: 'Войти',
                    btnClass: 'btn btn-primary btn-block btn-lg',
                    keys: ['enter'],
                    action: function() {
                        cmodal.$content.find('.errors').empty();
                        $.ajax({
                            type:'POST',
                            url: '/ajax_login/',
                            data: cmodal.$content.find('form').serialize(),
                            success: function(response) {
                                if (response.success) {
                                    self.attr('href', '/personal/');
                                    self.removeClass('personal-login');
                                    window.location = '/personal/';
                                } else {
                                    cmodal.$content.find('.errors').append('<p class="error">Укажите правильный логин и пароль.</p>')
                                }
                            }
                        });
                        return false;
                    }
                }
            }
        });
    });

    $('.offer-stripe .icon-close').click(function(e) {
        e.preventDefault();
        var self = $(this);
        setCookie('catreloc_announce_hidden', '1', 7200);
        self.parent().parent().slideUp();
        var height = self.parent().parent().height();
        $('body').animate({paddingTop: '-=' + height + 'px'}).removeClass('with-offer-stripe');
    });
})();

$('#Anonymous').click(function(e) {
    $.ajax({
        type:'POST',
        url: '/personal/anonymous/addremove/',
    })
});

$('#SwitchCheckNews').click(function(e) {
    $.ajax({
        type:'POST',
        url: '/personal/subscription/addremove/',
        data: {'subscription': 'news'},
    })
});

$('#SwitchCheckPromotions').click(function(e) {
    $.ajax({
        type:'POST',
        url: '/personal/subscription/addremove/',
        data: {'subscription': 'promotions'},
    });
});


$(document).keyup(function(e) {
    var selection = window.getSelection().toString();
    if (!(e.ctrlKey && e.key === 'Enter')) {
        return
    }
    if (e.ctrlKey && e.key === 'Enter') {
        if (selection == '') {
            return
        };
        var select = selection
        var href = window.location.href
        var box_width = '413px';
        var window_width = $(window).width();
        if (window_width < 1000) {
            box_width='100%';
        }
        if (select.length <= 47){
            var rows = 1;
        }
        $.confirm({
            title: 'Ошибка в тексте',
            backgroundDismiss: true,
            theme:'jo big',
            useBootstrap: false,
            draggable: false,
            content: '<form action="" method="post">' +
            '<p class="form_error" style="margin-top:0px">Ошибка</p>' +
            '<textarea name="misspelled_text" class="misspelled_text form-control" required rows="'+ rows +'" disabled>' + selection + ' </textarea>' +
            '<p class="form_error">Изменить</p>' +
            '<textarea name="revised_text" class="revised_text form-control" placeholder="Введите исправление" required rows="'+ rows +'">' + selection + ' </textarea>' +
            '<input name="href" class="href" type="hidden" value="' + href + '">' +
            '</form>',
            boxWidth: box_width,
            closeIcon: true,
            closeIconClass: 'close-icon',
            buttons: {
                formSubmit: {
                    text: 'Отправить изменения',
                    btnClass: 'btn-primary btn-block btn-selection',
                    action: function () {
                    var misspelled_text = this.$content.find('.misspelled_text').val();
                    var revised_text = this.$content.find('.revised_text').val();
                    var href = this.$content.find('.href').val();
                    $.post('/selection/add/', {
                        misspelled_text:misspelled_text,
                        revised_text:revised_text,
                        href:href
                        }).done(function() {
                            $.alert({
                                title:'',
                                titleClass:'sm',
                                useBootstrap:false,
                                animateFromElement:false,
                                boxWidth:'300px',
                                theme:'jo',
                                content:'Спасибо вам за вашу помощь!',
                                buttons: {
                                    'ok': {
                                        text: 'Закрыть',
                                        btnClass: 'btn-secondary btn-block',
                                    }
                                }
                            })
                        });
                    }
                }
            },
        });
	}
});


