//манипуляции с ответом апи
function api_response(response) {
    //console.log('api');
    if (response.data) {
        response.data.forEach(function (item) {
            //alert(item.method)
            if (item.method == 'append') {
                $(item.selector).append(item.content);
            }
            //если нужно редактировать ссылки передзаменой
            else if (item.method == 'append_change_url') {
                //console.log(item.content)
                var replaceArr = $('body').data('visitor_replace_arr');
                // Перебір кожного ключа-значення масиву JSON і заміна відповідних значень в $href
                $.each(replaceArr, function (key, value) {
                    var regex = new RegExp("{" + key + "}", "g");
                    item.content = item.content.replace(regex, value);
                });
                /*
                $.each(replaceArr, function(key, value) {
                    item.content = item.content.replace("{" + key + "}", value);
                });
                /**/
                $(item.selector).append(item.content);
            } else if (item.method == 'append_comment') {
                //если комент есть в доме то не вставляем
                if ($(item.selector + ' .message-wrap[data-id=' + item.id + ']').length == 0) {
                    $(item.selector).append(item.content);
                }
            } else if (item.method == 'prop') {
                $(item.selector).prop(item.content, item.val);
            } else if (item.method == 'before') {
                $(item.selector).before(item.content);
            } else if (item.method == 'prepend') {
                $(item.selector).prepend(item.content);
            } else if (item.method == 'scrollTop') {
                var div = $(item.selector);
                div.scrollTop(div.prop('scrollHeight'));
            } else if (item.method == 'show') {
                $(item.selector).show();
            } else if (item.method == 'hide') {
                $(item.selector).hide();
            } else if (item.method == 'fadeOut_remove') {
                $(item.selector).fadeOut("slow", function () {
                    $(item.selector).remove();
                });
            } else if (item.method == 'remove') {
                $(item.selector).remove();
            } else if (item.method == 'addClass') {
                $(item.selector).addClass(item.content);
            } else if (item.method == 'removeClass') {
                $(item.selector).removeClass(item.content);
            } else if (item.method == 'player_volume') {
                if (player) {
                    if (item.content) {
                        if ($('.is_admin').length == 0) {
                            console.log('on1');
                            player.increaseVolume(1);
                        } else {
                            console.log('off2');
                        }
                    } else {
                        console.log('off1');
                        player.decreaseVolume(1);
                    }
                }
            } else if (item.method == 'player_start') {
                if ($('body[data-layout="webinar_media"]').length) {
                    var $url = $('body').data('start')
                    //alert($url)
                    window.location.href = $url
                    //window.location.reload();
                } else {
                    player_start();
                }
            } else if (item.method == 'player_destroy') {
                if ($('body[data-layout="webinar_media"]').length) {
                    var $url = $('body').data('start')
                    //alert($url)
                    //console.log($url)
                    window.location.href = $url
                    //window.location.reload();
                } else {
                    player_destroy();
                }
            } else if (item.method == 'player2_start') {
                player2_start();
            } else if (item.method == 'player2_destroy') {
                player2_destroy();
            } else if (item.method == 'removeAttr') {
                $(item.selector).removeAttr(item.content);
            } else if (item.method == 'html') {
                $(item.selector).html(item.content);
            } else if (item.method == 'text') {
                $(item.selector).text(item.content);
            } else if (item.method == 'val') {
                $(item.selector).val(item.content);
            } else if (item.method == 'replaceWith') {
                $(item.selector).replaceWith(item.content);
            } else if (item.method == 'alert') {
                alert(item.content);
            } else if (item.method == 'beep') {
                beep();
            }
            //переадресация
            else if (item.method == 'location') {
                window.location.href = item.content;
            }
            //переадресация
            else if (item.method == 'location_percent') {
                //alert(item.percent)
                var randomValue = Math.random() * 100;
                //alert(randomValue)
                if (randomValue <= item.percent) {
                    var $visitor_info = $('body').data('visitorinfo')
                    /**/
                    if ($visitor_info != '') {
                        // Перевірка, чи посилання містить '?'
                        if (item.content.includes('?')) {
                            // Якщо містить, додайте '&'
                            item.content = item.content + '&visitor_info=' + encodeURIComponent($visitor_info);
                        } else {
                            // Якщо не містить, додайте '?'
                            item.content = item.content + '?visitor_info=' + encodeURIComponent($visitor_info);
                        }
                    }
                    window.location.href = item.content;

                }
            } else if (item.method == 'location_replace') {
                var $name = $('body').data('visitorname')
                var $phone = $('body').data('visitorphone')
                var $email = $('body').data('visitoremail')
                var $href = '';
                var $one = '';
                var $href = item.content;
                if ($href) {
                    // Замінює {name} на значення name
                    $href = $href.replace('{name}', $name);
                    // Замінює {email} на значення email
                    $href = $href.replace('{email}', $email);
                    // Замінює {phone} на значення phone
                    $href = $href.replace('{phone}', $phone);
                }
                window.location.href = $href;
            }
            //замена {name}, {email}, {phone} в ссылке
            else if (item.method == 'CheckLinkUserFilds') {
                var $name = $('body').data('visitorname')
                var $phone = $('body').data('visitorphone')
                var $email = $('body').data('visitoremail')
                var $href = '';
                var $one = '';
                if (item.content == 'bnn_bottom') {
                    var $one = $('.js_one_bs');
                } else if (item.content == 'selling_button1') {
                    var $one = $('.selling_button[data-place=1] a');
                } else if (item.content == 'selling_button2') {
                    var $one = $('.selling_button[data-place=2] a');
                }
                if ($one) {
                    var $href = $one.attr('href');
                    if ($href) {
                        /*
                        //alert($href)
                        // Замінює {name} на значення name
                        $href = $href.replace('{name}', $name);
                        // Замінює {email} на значення email
                        $href = $href.replace('{email}', $email);
                        // Замінює {phone} на значення phone
                        $href = $href.replace('{phone}', $phone);
                        /**/
                        /**/
                        // Отримання масиву JSON з атрибуту data-visitor_replace_arr
                        var replaceArr = $('body').data('visitor_replace_arr');
                        // Перебір кожного ключа-значення масиву JSON і заміна відповідних значень в $href
                        $.each(replaceArr, function (key, value) {
                            $href = $href.replace("{" + key + "}", value);
                        });
                        /**/

                        $one.attr('href', $href);

                    }
                }
            } else if (item.method == 'location_percent_no_admin') {
                if (!$('body').hasClass('authorizated')) {
                    //alert(item.percent)
                    var randomValue = Math.random() * 100;
                    //alert(randomValue)
                    if (randomValue <= item.percent) {
                        var $visitor_info = $('body').data('visitorinfo')
                        /**/
                        if ($visitor_info != '') {
                            // Перевірка, чи посилання містить '?'
                            if (item.content.includes('?')) {
                                // Якщо містить, додайте '&'
                                item.content = item.content + '&visitor_info=' + encodeURIComponent($visitor_info);
                            } else {
                                // Якщо не містить, додайте '?'
                                item.content = item.content + '?visitor_info=' + encodeURIComponent($visitor_info);
                            }
                        }
                        window.location.href = item.content;
                        /**/
                    }
                }
            }
            //обновление
            else if (item.method == 'reload') {
                window.location.reload();
            }
            //окно, тут заменить на свое окно если не бутстрап
            else if (item.method == 'modal') {
                if (item.content) $(item.selector).modal(item.content);
                else $(item.selector).modal();
            } else if (item.method == 'scroll') {
                //скрол
                $('html, body').animate({
                    scrollTop: $(item.selector).offset().top
                }, 1000);
            }
            //выполнение любого скрипта
            else if (item.method == 'script') {
                $('body').append(item.content);
            }
            //окно свит алерт
            else if (item.method == 'swal') {
                var icon = 'error';
                if (item.icon) icon = item.icon;
                Swal.fire({
                    title: item.content,
                    icon: icon
                })
            }
            //тригер
            else if (item.method == 'trigger') {
                $(item.selector).trigger(item.content);
            }
            //запуск таймера
            else if (item.method == 'speaker_timer_start') {
                speaker_timer_start();
            } else {
                alert(item.method);
            }
        });
    }
    //todo код с ошибкой, сделать в всплывающем окне
    if (response.error_text) {
        alert(response.error_text);
    } else {
        if (response._error) alert(response._error);
    }
}

var speaker_timer_on = false,
    speaker_time_start = 0;

function speaker_timer() {
    var diff = parseInt(Date.now() / 1000) - speaker_time_start,
        sec = 0,
        min = 0;
    if (diff > 59) {
        sec = diff % 60;
        min = (diff - sec) / 60;
    } else sec = diff;
    if (sec < 10) sec = '0' + sec;
    if (min < 10) min = '0' + min;
    $('.timer').html(min + ':' + sec);
}

function speaker_timer_start() {
    speaker_time_start = parseInt(Date.now() / 1000);
    speaker_timer_on = setInterval(() => speaker_timer(), 1000);
}


function beep() {
    var snd = new Audio("/templates/src/audio/beep.mp3");
    //console.log('beep');
    snd.play();
}

$(document).ready(function () {
    let $languages = $('.js_script_languages').html()
    $languages = JSON.parse($languages);
    //alert($languages.edit_inputs)
    //console.log($languages)
    /*
     alert($languages)
     /**/

    $(document).on('input', '.js_current_time input', function () {
        var $val = $(this).val()
        $val = parseInt($val)
        if ($val < 0) {
            $(this).val('')
        }
    })



    //валидация форм
    if ($.isFunction($.fn.validate)) {
        $('form.validate').each(function () {
            $(this).validate({
                //настройка стилей валидации
                //.form-group обертка для всех полей
                errorPlacement: function (error, element) {
                    error.appendTo(element.closest(".form-group"));
                },
                highlight: function (element, errorClass, validClass) {
                    //console.log('highlight');
                    $(element).addClass(errorClass);
                    $(element).closest('.form-group').addClass(errorClass);
                },
                unhighlight: function (element, errorClass, validClass) {
                    //console.log('unhighlight');
                    $(element).removeClass(errorClass);
                    $(element).closest('.form-group').removeClass(errorClass);
                }
            })
        });
    }

    //очитска урл от путстых значений
    $('form.form_clear').submit(function () {
        $(this).find('select,input').each(function () {
            if ($(this).val() == '' || $(this).val() == '0-0') $(this).removeAttr('name');
        });
    });

    //отправка формы аджаксом - v1.2.22
    $(document).on('submit', 'form.ajax', function () {
        var form = $(this),
            formData = new FormData($(this).get(0)),
            //путь куда отправляется форма
            action = $(this).data('action'),
            //окно которое открывается при успехе
            //window_success = $(this).data('window_success'),
            //блок куда показывать ошибки сгенерированные на пхп
            //message_box = $('.message_box',this),
            valid = true;
        //обработку делаем только если указан data-action, иначе форма ведет себя как обычная
        if (action) {
            //валидация
            if ($(this).hasClass('validate')) {
                //jquery_validate.js
                if ($.isFunction($.fn.validate)) {
                    valid = false;
                    if ($(this).valid()) {
                        valid = true;
                    }
                }
            }
            //делаем отправку только если форма валидная
            if (valid) {
                $.ajax({
                    url: action,
                    type: $(form).attr('method'),
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    data: formData,
                    cache: false,
                    beforeSend: function () {
                        $(form).find('button[type=submit]').addClass('disabled');
                        if ($(form).data('action') == '/api/chat/') {
                            $('textarea', form).prop('value', null).removeAttr('style');
                        }
                    },
                    success: function (json, textStatus) {
                        //очистка формы
                        if (json.success) {
                            $('input:not([type=submit]):not([name=captcha]):not([type=hidden]),textarea,select', form).prop('value', null);
                        }
                        api_response(json);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                        setTimeout(function () {
                            $(form).find('button[type=submit]').removeClass('disabled');
                        }, 1000);
                    }
                });
            }
            return false;
        }
    });

    //аналоги form.ajax не для форм (ссылки, кнопки и т.д.)
    $(document).on('click', '[data-api*="/"]', function (e) {
        e.preventDefault();
        var $data = $(this).data(),
            $url = $data.api,
            $btn = $(this);
        //если уже нажали и небыло ответа аджакса то ничего не делать
        if (!$btn.hasClass('js_wait')) {
            $btn.addClass('js_wait');
            //удаляем датаатрибут чтобы не дублировать в запросе
            delete $data.api;
            $.ajax({
                method: "GET",
                type: 'JSON',
                url: $url,
                data: $data,
                cache: false
            }).done(function ($response) {
                api_response($response);
            }).fail(function () {
                alert("error");
            }).always(function () {
                $btn.removeClass('js_wait');
            });
            //возвращаем назад дата атрибут
            $data.api = $url;
        }
        //return false;
    });

    //мультичексбокс
    $(document).on("change", '.form_multi_checkbox .data input', function () {
        var arr = [];
        var i = 0;
        $(this).parents('.data').find('input:checked').each(function () {
            arr[i] = $(this).val();
            i++;
        });
        $(this).parents('.data').next('input').val(arr);
    });
    //min-max
    $(document).on("change", '.form_input2 input', function () {
        var min = parseInt($(this).parents('.form_input2').find('input.form_input2_1').val());
        var max = parseInt($(this).parents('.form_input2').find('input.form_input2_2').val());
        $(this).parents('.form_input2').find('input[type=hidden]').val(min + '-' + max);
    });


    //v1.2.64 пагинатор на ajax
    $(document).on("click", '.pagination_ajax .pagination a', function () {
        var url = $(this).attr('href'),
            box = $(this).closest('.pagination_ajax');
        $.post(url, {
            action: 'ajax',
        }, function (data) {
            $(box).replaceWith(data);
            //добавляем в историю браузера
            //window.history.pushState(null, null, url);
        });
        return false;
    });
    //автоматическая догрузка страниц для ajax_more
    if ($('.pagination_ajax').length) {
        var pagination_ajax_url = ''; //v1.2.90
        $('.pagination a', '.pagination_ajax').trigger('click');
        $(window).scroll(function () {
            //console.log('scroll');
            if ($('.pagination_ajax').length) {
                var box = $('.pagination_ajax'),
                    document_top = $(document).scrollTop(),
                    window_height = $(window).height(),
                    box_top = $(box).offset().top,
                    box_height = $(box).height(),
                    current_url = $('.pagination a', box).attr('href');
                if (document_top + window_height > box_top && document_top - box_top < box_height) {
                    if (current_url != pagination_ajax_url) { //v1.2.90
                        $('.pagination a', box).trigger('click');
                        pagination_ajax_url = current_url; //v1.2.90
                    }
                }
            }
        });
    }
    /**/

    //удаление записи
    $(document).on('click', '.js-delete', function () {
        var title = $(this).data('question');
        if (title === undefined) title = $languages.want_delete; //'Вы действительно хотите удалить вебинар?'
        Swal.fire({
                title: title,
                //text: '',
                icon: 'error',
                cancelButtonText: $languages.cancel,
                confirmButtonText: $languages.confirm,
                showCancelButton: true
                //dangerMode: true
            })
            .then((result) => {
                if (result.value) {
                    var row = $(this).closest('.js-parent'),
                        m = row.data('module'),
                        id = row.data('id'),
                        path = '/api/delete/?module=' + m + '&id=' + id;
                    $.getJSON(path, {},
                        function (data) {
                            api_response(data);
                        }
                    )
                } else {

                }
            });
        /*
         Swal.fire({
         title: 'Are you sure?',
         text: "You won't be able to revert this!",
         icon: 'warning',
         showCancelButton: true,
         confirmButtonColor: '#3085d6',
         cancelButtonColor: '#d33',
         confirmButtonText: 'Yes, delete it!'
         }).then((result) => {
         if (result.value) {
         Swal.fire(
         'Deleted!',
         'Your file has been deleted.',
         'success'
         )
         }
         })
         */

        return false;
    });

    $(document).on("change", ".color_input .js_color_input", function () {
        var $val = $(this).val()
        $(this).closest('.color_input').find('.main_input').val($val)
    })
    if (typeof (mask) === "function") {
        $('.js_color_mask').mask('#******');
    }
    $(document).on("change", ".color_input .js_color_mask", function () {
        var $val = $(this).val()
        $(this).closest('.color_input').find('.js_color_input').val($val)
    })

    /*
     */

    $(document).on('click', '.modal_header_list .modal-title', function () {
        var $k = $(this).data('k')
        $('.modal_header_list .modal-title').removeClass('active')
        $(this).addClass('active')
        $(this).closest('.modal').find('.one_block').hide()
        $(this).closest('.modal').find('.one_block[data-k=' + $k + ']').show()
    })

    $(document).on('submit', '#html_form form', function (event) {
        event.preventDefault();
        var formData = $(this).serialize();
        var formMethod = $(this).attr("method") || "GET"; // Default to GET
        $('#html_form .form_submited').show()
        $('#html_form .info_form').hide()
        $.ajax({
            type: formMethod,
            url: $(this).attr("action"),
            data: formData,
            success: function (response) {
                //alert(111)
            }
        });

    })

    function simulateDOMContentLoaded() {
        var event = new Event('DOMContentLoaded', {
            bubbles: true,
            cancelable: true,
        });
        document.dispatchEvent(event);
    }

    $(document).on('click', '.js_form_test', function (e) {
        e.preventDefault()
        var $html = $(this).closest('.one_button').find('textarea[name*=html_form]').val()
        $('#html_form .form_submited').hide()
        $('#html_form .info_form').show()
        $('#html_form').modal()
        $('#html_form .info_form').html($html)
        setTimeout(function () {
            simulateDOMContentLoaded()
        }, 800);

        // Викликати функцію після додавання твого коду
        //simulateDOMContentLoaded();
    })

    $(document).on('change', 'select[name*=reaction]', function () {
        var $val = $(this).val()
        if ($val == 1) {
            $(this).closest('.one_button').find('.html_form').addClass('active')
            $(this).closest('.one_button').find('textarea[name*=html_form]').addClass('required')

            $(this).closest('.one_button').find('.button_href').addClass('hide')


        } else if ($val == 0) {
            $(this).closest('.one_button').find('.html_form').removeClass('active')
            $(this).closest('.one_button').find('textarea[name*=html_form]').removeClass('required')

            $(this).closest('.one_button').find('.button_href').removeClass('hide')
        }
    })

    $(document).on('input', 'textarea[name*=html_form], textarea[name*=html_code]', function () {
        var $html_form = $(this).val();
        var $k = $(this).closest('.html_form').data('k')
        $.ajax({
            method: "POST",
            type: 'JSON',
            url: '/api/check_html_form/',
            data: {
                'text': $html_form,
                'k': $k
            },
            success: function (json, textStatus) {
                api_response(json);
            }
        })
    })


    $(document).on('change', '.js_display_instinct', function () {
        console.log(2)
        var $instinct = $(this).data('instinct')
        //alert('db-'+$k)
        var $webinar = $(this).data('webinar')
        var $val = 0;
        if ($(this).prop('checked')) {
            var $val = 1;
        }
        /*
        if ($val) {
            $('.js_one_sell_bnn[data-k=' + $k + '] .js_sell_display').prop("checked", true);
            $('.js_one_bnn[data-k=' + $k + '] .js_bnn_display').prop("checked", true);
        } else {
            $('.js_one_sell_bnn[data-k=' + $k + '] .js_sell_display').prop("checked", false);
            $('.js_one_bnn[data-k=' + $k + '] .js_bnn_display').prop("checked", false);
        }
        /**/
        $.ajax({
            method: "POST",
            type: 'JSON',
            url: '/api/common/chat/',
            data: {
                action: 'change_instinct',
                'instinct': $instinct,
                'value': $val,
                'webinar': $webinar
            },
            success: function (json, textStatus) {
                //api_response(json);
            }
        })
    })



    $(document).on('change', '.js_display_button', function () {
        console.log(1)
        var $k = $(this).data('k')
        //alert('db-'+$k)
        var $webinar = $(this).data('webinar')
        var $val = 0;
        if ($(this).prop('checked')) {
            var $val = 1;
        }
        /**/
        if ($val) {
            $('.js_one_sell_bnn[data-k=' + $k + '] .js_sell_display').prop("checked", true);
            $('.js_one_bnn[data-k=' + $k + '] .js_bnn_display').prop("checked", true);
        } else {
            $('.js_one_sell_bnn[data-k=' + $k + '] .js_sell_display').prop("checked", false);
            $('.js_one_bnn[data-k=' + $k + '] .js_bnn_display').prop("checked", false);
        }
        /**/
        $.ajax({
            method: "POST",
            type: 'JSON',
            url: '/api/common/chat/',
            data: {
                action: 'selling_buttons',
                'button_key': $k,
                'value': $val,
                'webinar': $webinar
            },
            success: function (json, textStatus) {
                //api_response(json);
            }
        })
    })

    $(document).on('change', '.js_sell_display', function () {
        console.log(2)
        var $k = $(this).closest('.js_one_sell_bnn').data('k')
        var $webinar = $(this).closest('.js_one_sell_bnn').data('webinar')
        var $val = 0;
        if ($(this).prop('checked')) {
            var $val = 1;
            //alert($k)
            /*
            $('.js_sell_display').each(function(){
                var $one_k = $(this).closest('.js_one_sell_bnn').data('k')
                if($one_k != $k && $(this).prop('checked')){
                    $(this).prop('checked',false)
                }
            })
            /**/
        }
        /**/
        if ($val) {
            $('.js_display_button[data-k=' + $k + ']').prop("checked", true);
        } else {
            $('.js_display_button[data-k=' + $k + ']').prop("checked", false);
        }
        //alert($k+'-'+$val+'-'+$webinar)
        /**/
        $.ajax({
            method: "POST",
            type: 'JSON',
            url: '/api/common/chat/',
            data: {
                action: 'selling_buttons',
                'button_key': $k,
                'value': $val,
                'webinar': $webinar
            },
            success: function (json, textStatus) {
                //api_response(json);
            }
        })
        /**/
    })
    $(document).on('click', '.js_add_instinct', function () {
        var $content = $('#webinar_list_herd').val()
        $('.list_herd_data').prepend($content)
    })
    $(document).on('click', '.js_delete_instinct', function () {
        $(this).closest('.input_wrap').remove()
    })



    $(document).on('click', '.js_add_webhook', function () {
        var $content = $('#webinar_webhook').val()
        $('.list_webhooks').append($content)
    })
    $(document).on('click', '.js_delete_webhook', function () {
        $(this).closest('.input_wrap').remove()
    })
    $('.webinar_additionally_block ').each(function (e) {
        let webinarBlockItem = $(this).find('.add_one_sell_btn');
        let webinarBlockItemFirst = webinarBlockItem.filter(':first')
        webinarBlockItemFirst.find('.one_button').show();
        webinarBlockItemFirst.find('.add_one_sell_btn_button').addClass('active')
    });
    $('.add_one_sell_btn_button').on('click', function () {
        $(this).toggleClass('active');
        $(this).parents('.add_one_sell_btn').find('.one_button').slideToggle()
    })

    function pin_one_comment($pin, title) {
        Swal.fire({
                title: title,
                //text: '',
                icon: 'error',
                cancelButtonText: $languages.cancel,
                confirmButtonText: $languages.confirm,
                showCancelButton: true
                //dangerMode: true
            })
            .then((result) => {
                if (result.value) {

                    var webinar = $pin.data('webinar'),
                        comment = $pin.data('id');
                    if ($pin.closest('.js-parent').hasClass('pinned')) {
                        var action = 'unpin';
                    } else {
                        var action = 'pin';
                    }
                    $.ajax({
                        url: '/api/webinar_pin_comment/',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            'webinar': webinar,
                            'comment': comment,
                            'action': action
                        },
                        cache: false,
                        beforeSend: function () {

                        },
                        success: function (json, textStatus) {
                            api_response(json);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(errorThrown);
                        },
                        complete: function (XMLHttpRequest, textStatus) {}
                    });
                    /**/
                    return false;
                } else {

                }
            });


    }
    $(document).on('click', '.js-pin', function (e) {
        e.preventDefault()
        var $pin = $(this)
        title = $languages.want_unpin;
        pin_one_comment($pin, title)
        return false;
    })
    $(document).on('click', '.pin_wrapper', function () {
        //$('.pin_wrapper').not(this).removeClass('show');
        //$(this).toggleClass('show');
        var $pin = $(this)
        title = $languages.want_pin;
        pin_one_comment($pin, title)
        return false;
    })
    $(document).on('click', '.js-pin', function () {
        $('.pin_wrapper').removeClass('show');
    })
    $(document).on('click', function (e) {
        if (!$(e.target).closest(".pin_wrapper_btn").length) {
            $('.pin_wrapper').removeClass('show');
        }
    });




});