

// WhatsApp-Tlgt Web
$(function () {
    window.isMobile = /Mobile|webOS|BlackBerry|IEMobile|MeeGo|mini|Fennec|Windows Phone|Android|iP(ad|od|hone)/i.test(navigator.userAgent);
    var nint = setInterval(function () {
        if ($('#whatsapp_button').length == 0) {
            if ($(".user-phone-widget").length) {
                var phone = $('.user-phone span[data-reactid=".0.1.1.0.0.2.5.2"]').text().replace(/\D+/g, '');
                if (phone[0] == 3 && phone.length == 10) phone = "39" + phone;
                if (phone[0] == 9 && phone.length == 10) phone = "7" + phone;
                if (phone[0] == 8 && phone.length == 11) phone = "7" + phone.slice(1);
                phone = "+" + phone;
                $(".user-phone-widget").after(`
                <span>
                <button id="whatsapp_button" class="btn btn-sm btn-default" onclick="window.open((window.isMobile ? 'https://wa.me/' : 'https://web.whatsapp.com/send?phone=') + '${phone}')" style="
                margin: 3px 0;
                background-color: #25D366;
                color: white;
                padding: 4px 5px;
                border: none;
                border-radius: 30px;
                height: 22px;
                "><svg aria-hidden="true" focusable="false" data-prefix="fab" data-icon="whatsapp" class="svg-inline--fa fa-whatsapp fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" style="width: 12px;"><path fill="currentColor" d="M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7.9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z"></path></svg>
                </button>
                <button id="whatsapp_button" class="btn btn-sm btn-default" onclick="window.open(('https://t.me/') + '${phone}')" style="
                padding: 4px 5px;    
                border: none;    
                height: 22px;
                width: 22px;
                background: url(https://upload.wikimedia.org/wikipedia/commons/8/82/Telegram_logo.svg);
                background-size: cover;
                background-repeat: no-repeat;
                ">

                </span>`);
            }
        }
    }, 50);
});
// WhatsApp-Tlgt Web

// Превью в хранилище

// Превью в хранилище
if (window.location.href.indexOf('/fileservice/control/account/') > -1) {
    $(function () {
        $('#w5-container table tr').each(function (i, row) {
            let filetype = $(row).find("td:nth-child(4)").text().trim();
            let filelink = $(row).find("td:nth-child(3) a").attr("href");
            if (["изображение", "image"].indexOf(filetype) > -1) {
                let thumb_img = "";
                if ([".gif", ".svg"].indexOf(filelink.substring(filelink.length - 4)) == -1) {
                    let regex = /(.*)\/fileservice\/file\/download(?:\/.*\/)(\d*)\/.*\/(\d*)\/.*\/((?:.*)\w{32}[^\/]*)/gm;
                    let thumb_subst = `$1/fileservice/file/thumbnail/h/$4/s/200x/a/$2/sc/$3`;
                    thumb_img = filelink.replace(regex, thumb_subst);
                } else {
                    thumb_img = filelink;
                }
                $(row).find("td:nth-child(3)").append('<img src="' + thumb_img + '" style="display:block;max-width:200px;" />');
            } else if (["видео", "video"].indexOf(filetype) > -1 || !isNaN(parseInt(filetype))) {
                $(row).find("td:nth-child(3)").append('<video controls src="' + filelink + '" style="display:block;width:200px;height:112px;" />');
            }
        });
    });
}
//------------------------------------------------------------------------------------------------
// Превью в хранилище

//  Показ ссылки для скачивания, при загрузке файла в ФХ
$(() => {
    if (window.location.href.indexOf('/fileservice/control/account/storage') > -1) {
        $('.uploadify-container').data('uploadifive').settings.onUploadComplete = function (e, res) {
            let $item = e.queueItem;
            let link = '/fileservice/control/account/file-by-hash?hash=' + res + '&from=storage'
            $item.find('.fileinfo').html(` <a target="_blank" href="${link}">${res}</a> `,);
            $.get(link, (data) => {
                var pageDom = $('<x/>').append($.parseHTML(data));
                newlink = pageDom.find('input.form-control[type="text"]').val();
                let linke = document.createElement('div');
                let linkc = document.createElement('a');
                $item.find('.filename').before(linke, linkc);
                $(linke).html(newlink)
                    .css({"position": "absolute", "left": "-99999px"});
                $(linkc).html('<i class="fa fa-clipboard" aria-hidden="true"></i> ')
                    .css({"cursor": "pointer"})
                    .on('click', function () {
                        selectElement(linke);
                        $(linke).select();
                        document.execCommand('copy');
                        let that = this;
                        $(that).css('color', '#ff00db');
                        setTimeout(() => {
                            $(that).css('color', '');
                        }, 1000);
                    });
            });

            function selectElement(element) {
                if (window.getSelection) {
                    var sel = window.getSelection();
                    sel.removeAllRanges();
                    var range = document.createRange();
                    range.selectNodeContents(element);
                    sel.addRange(range);
                } else if (document.selection) {
                    var textRange = document.body.createTextRange();
                    textRange.moveToElementText(element);
                    textRange.select();
                }
            }
        }
    }
});
//  Показ ссылки для скачивания, при загрузке файла в ФХ

//  Добавляет возможность перетаскивать блоки настроек в редакторе страниц и уроков

if (
    window.location.pathname.indexOf("/pl/cms/page/editor") > -1 ||
    (
        window.location.pathname == "/pl/teach/control/lesson/view" &&
        window.location.search.indexOf("editMode=1") > -1
    )
) {
    $(document).ajaxSuccess(function (event, xhr, settings) {
        if (settings.url.indexOf("/pl/lite/block/get-setting") > -1 || settings.url.indexOf("/pl/lite/block/settings") > -1) {
            setTimeout(() => {
                $('.setting-editor-popover, .block-style-popover')
                    .draggable({handle: '.popover-title', cancel: '.btn, input'})
                    .find('.popover-title').css({'cursor': 'move'});
            });
        }
    });
}


//РЕКЛАМНАЯ ПЛАШКА-----------------------------------------------------------------------------------------------

// Чтобы исключить отображение для определенной страницы, добавьте путь в массив excludedPages через запятую.
// Например: ["/cms/system/login", "/another/page", "/some/other/page", "/anticelulitic_booster_login"];
/*
const excludedPages = ["/webinar_live", "/test_drive_renasterea", "/photo_quiz", "/ap_1", "/ap_2", "/ap_3", "/ap_redirect", "/upsell_2bundle", "/1-antrenament", "/cadou_inst", "/bundles-5", "/voting_concurs_baza", "/waitlist_campaign_ticket", "/cms/system/login", "/pl/webinar/show", "/postura_login", "/giftshop", "/live12", "/cadou_personalizat" , "/anticelulitic_booster_login" , "/summer_pre_sale2025_anketa" , "/summer_pre_sale_quest", "/bundle2" , "/webinar_renasterea_35plus"];
if (!excludedPages.includes(window.location.pathname)) {

	var chek = $('#ltBlock2132901984, #ltBlock2140587928, #ltBlock2140590587, #ltBlock2140182520, #ltBlock2140590589, #ltBlock2140605949, #ltBlock2133973149, #ltBlock2137443900, #ltBlock2136546957, #ltBlock2132901220, #ltBlock2132895141, #ltBlock2132893775, #ltBlock2132892340, #ltBlock2126167824, #ltBlock2130863830, #ltBlock2132299975, #ltBlock2132299973, #ltBlock2130863836, #ltBlock2130863853, #ltBlock2128326127, #ltBlock2129369047, #ltBlock2129369028, #ltBlock2129371233, #ltBlock2128372988, #ltBlock2126900333, #ltBlock2126899872, #ltBlock2126168380, #ltBlock2126169168, #ltBlock2126171729, #ltBlock2126172075, #ltBlock1937542033, #ltBlock2124343811, #ltBlock2124994490, #ltBlock2123278655, #ltBlock1937542039, #ltBlock1937565731, #ltBlock1937565736, #ltBlock1937565741, #ltBlock1937565753, #ltBlock2038061570, #ltBlock2038061606, #ltBlock2120025879, #ltBlock2120027080, #ltBlock2122702373, #ltBlock2122702375, #ltBlock2120768734, #ltBlock2120768898, #ltBlock2120768964, #ltBlock2120769118, #ltBlock2120769249, #ltBlock2120769302, #ltBlock2120769375, #ltBlock2120769411, #ltBlock2122702366, #ltBlock2122702370, #ltBlock1402021907, #ltBlock2117268908, #ltBlock2116414930, #ltBlock2116414931, #ltBlock2116414932, #ltBlock2116414933, #ltBlock2116414934, #ltBlock2112327716, #ltBlock2112327717, #ltBlock2112327722, #ltBlock2112327723, #ltBlock2112327725, #ltBlock2108534039, #ltBlock2108531113, #ltBlock2108533641, #ltBlock1402021905, #ltBlock1393928712, #ltBlock1393928701, #ltBlock1384786157, #ltBlock1384786150, #ltBlock1383340787, #ltBlock1383340778, #ltBlock1383340769, #ltBlock1383340763, #ltBlock1380605761, #ltBlock1380605719, #ltBlock1380605650, #ltBlock1380605597, #ltBlock1380604484, #ltBlock1380604476, #ltBlock1413136954, #ltBlock1278614406, #ltBlock1278614438, #ltBlock1462368139, #ltBlock1462368129, #ltBlock1461171663, #ltBlock1461171663, #ltBlock1493594782, #ltBlock1423485245, #ltBlock1418501198, #ltBlock1418501473, #ltBlock1297183951, #ltBlock1502582191, #ltBlock1509590002, #ltBlock1509596145, #ltBlock1509594466, #ltBlock1461171666, #ltBlock1520414441, #ltBlock1520414457, #ltBlock1519935700, #ltBlock1519935591, #ltBlock1519935703, #ltBlock1225658984, #ltBlock1560124695, #ltBlock1560124703, #ltBlock1560124716, #ltBlock1560124883, #ltBlock1560124887, #ltBlock1560124891, #ltBlock1560203908, #ltBlock1568414730, #ltBlock1568414749, #ltBlock1570460057, #ltBlock1570460073, #ltBlock1572846984, #ltBlock1572846989, #ltBlock1576220208, #ltBlock1588353094, #ltBlock1605587775, #ltBlock1605605122, #ltBlock1626485691, #ltBlock1626485704, #ltBlock1626485734, #ltBlock1626485747, #ltBlock1631126615, #ltBlock1631279668, #ltBlock1631280295, #ltBlock1631408673, #ltBlock1645760526, #ltBlock1645760385, #ltBlock1645760126, #ltBlock1645732348, #ltBlock1645732346, #ltBlock1645732342, #ltBlock1645732246, #ltBlock1645732228, #ltBlock1645732226, #ltBlock1655577867, #ltBlock1655577863, #ltBlock1655577859, #ltBlock1647285938, #ltBlock1631126615, #ltBlock1656794369, #ltBlock1631408673, #ltBlock1656941096, #ltBlock1656941098, #ltBlock1691674459, #ltBlock1691674469, #ltBlock1691674471, #ltBlock1691674473, #ltBlock1711410036, #ltBlock1711410041, #ltBlock1711410044, #ltBlock1711411447, #ltBlock1711411449, #ltBlock1711411455, #ltBlock1711412947, #ltBlock1746107545, #ltBlock1747591530, #ltBlock1747591787, #ltBlock1747591828, #ltBlock1725488139, #ltBlock1725488143, #ltBlock1748292243, #ltBlock1748302985, #ltBlock1725488147, #ltBlock1761061407, #ltBlock1770668385, #ltBlock1770668569, #ltBlock1722192147, #ltBlock1722192557, #ltBlock1722192559, #ltBlock1805928687, #ltBlock1810907229, #ltBlock1810907349, #ltBlock1812063541, #ltBlock1816279626, #ltBlock1816279707, #ltBlock1816279709, #ltBlock1816211989, #ltBlock1816279762, #ltBlock1816279783, #ltBlock1816279804, #ltBlock1816212076, #ltBlock1816279896, #ltBlock1816279900, #ltBlock1816279920, #ltBlock1816212090, #ltBlock1816279956, #ltBlock1816279982, #ltBlock1816279986, #ltBlock1816212101, #ltBlock1816280342, #ltBlock1816280371, #ltBlock1816280384, #ltBlock1816212116, #ltBlock1816280463, #ltBlock1816280472, #ltBlock1816280483, #ltBlock1816212114, #ltBlock1816280553, #ltBlock1816280563, #ltBlock1816280569, #ltBlock1816212143, #ltBlock1816280640, #ltBlock1816280654, #ltBlock1816280656, #ltBlock1812078710, #ltBlock1812105435, #ltBlock1813352310, #ltBlock1813354061, #ltBlock1816233745, #ltBlock1816233839, #ltBlock1816233689, #ltBlock1810704806, #ltBlock1877351211, #ltBlock1877351203, #ltBlock1877351139, #ltBlock1876790703, #ltBlock1876790701, #ltBlock1876790695, #ltBlock1869086245, #ltBlock1869086238, #ltBlock1869086208, #ltBlock1899556077, #ltBlock1899636946, #ltBlock1899645893, #ltBlock1899649269, #ltBlock1899650588, #ltBlock1899651377, #ltBlock1927206709, #ltBlock1927194200, #ltBlock1934583121, #ltBlock1934583122, #ltBlock1937542033, #ltBlock1937542039, #ltBlock1937565731, #ltBlock1937565736, #ltBlock1937565741, #ltBlock1937565753, #ltBlock1931688940, #ltBlock1931688972, #ltBlock1942391867, #ltBlock1942392146, #ltBlock1942392600, #ltBlock1948712255, #ltBlock1948715740, #ltBlock1945384674, #ltBlock1945384673, #ltBlock1945384670, #ltBlock1945384669, #ltBlock1945384655, #ltBlock1945384653, #ltBlock1945384651, #ltBlock1945384649, #ltBlock1945384639, #ltBlock1945384635, #ltBlock1944219173, #ltBlock1944218726, #ltBlock1951854996, #ltBlock1952087599, #ltBlock1953671114, #ltBlock1953671117, #ltBlock1954999716, #ltBlock1954999719, #ltBlock1955678917, #ltBlock1956337613, #ltBlock1956540592, #ltBlock1958587770, #ltBlock1958638516, #ltBlock1958641054, #ltBlock1958641478, #ltBlock1741412006, #ltBlock1961294867, #ltBlock1965367163, #ltBlock1965367202, #ltBlock1965367212, #ltBlock1910713159, #ltBlock1971133906, #ltBlock1971135457, #ltBlock1971135459, #ltBlock1971993726, #ltBlock1920918401, #ltBlock1920918402, #ltBlock1920918403, #ltBlock1974690057, #ltBlock1974690041, #ltBlock952528400, #ltBlock952528399, #ltBlock1900639553, #ltBlock1120848286, #ltBlock1120848287, #ltBlock1979651076, #ltBlock1979651145, #ltBlock1979651169, #ltBlock1979797381, #ltBlock1979797382, #ltBlock1982337706, #ltBlock1971993726, #ltBlock1982340658, #ltBlock1982340689, #ltBlock1982340690, #ltBlock1980419121, #ltBlock1981136075, #ltBlock1980902341, #ltBlock1980419123, #ltBlock1980418548, #ltBlock1982385592, #ltBlock1982385707, #ltBlock1982386114, #ltBlock1980418862, #ltBlock1982385587, #ltBlock1982385692, #ltBlock1982385855, #ltBlock1980418881, #ltBlock1982385565, #ltBlock1982385678, #ltBlock1982385844, #ltBlock1980418891, #ltBlock1982385551, #ltBlock1982385677, #ltBlock1982385832, #ltBlock1980418955, #ltBlock1982385540, #ltBlock1982385674, #ltBlock1982385789, #ltBlock1980418982, #ltBlock1982385495, #ltBlock1982385644, #ltBlock1982385778, #ltBlock1980419043, #ltBlock1982385487, #ltBlock1982385619, #ltBlock1982385770, #ltBlock1980419075, #ltBlock1982385485, #ltBlock1982385611, #ltBlock1982385735, #ltBlock1989781815, #ltBlock1992911044, #ltBlock1992911045, #ltBlock1992911046, #ltBlock1992911047, #ltBlock1993336701, #ltBlock1993339136, #ltBlock1994071252, #ltBlock1994071253, #ltBlock1996849439,#ltBlock1996849441, #ltBlock2005604039, #ltBlock1959417643, #ltBlock2007627091, #ltBlock2007629134, #ltBlock2007629135, #ltBlock2010856602, #ltBlock2010856614, #ltBlock2011436821, #ltBlock2011436829, #ltBlock1719591885, #ltBlock2021773265, #ltBlock2021780771, #ltBlock2021780782, #ltBlock2021780787, #ltBlock2021780789, #ltBlock2021780791, #ltBlock1647527930, #ltBlock1647528816, #ltBlock1647528810, #ltBlock1647517158, #ltBlock1985938993, #ltBlock2026051647, #ltBlock2022121927, #ltBlock2032707544, #ltBlock2032723123, #ltBlock2034404261, #ltBlock2036007470, #ltBlock2036719820, #ltBlock2036007569, #ltBlock2036743117, #ltBlock2036007591, #ltBlock2036007592, #ltBlock2036007647, #ltBlock2036007648, #ltBlock2038060573, #ltBlock2038061570, #ltBlock2038061581, #ltBlock2038061606, #ltBlock2038061614, #ltBlock2038061616, #ltBlock2038077267, #ltBlock2038077269, #ltBlock2039210939, #ltBlock2041318138, #ltBlock2041318139, #ltBlock2041318140, #ltBlock2046009816, #ltBlock2049754466, #ltBlock2049754468, #ltBlock2049754470, #ltBlock2050455615, #ltBlock2050457686, #ltBlock2050457898, #ltBlock2050460460, #ltBlock2050457892, #ltBlock2041158178, #ltBlock2049633667, #ltBlock2041149327, #ltBlock2041164043, #ltBlock2049639785, #ltBlock2041150911, #ltBlock2050469853, #ltBlock2050670697, #ltBlock2050673516, #ltBlock2050675619, #ltBlock2050676531, #ltBlock2050676606, #ltBlock2050678713, #ltBlock2050678825, #ltBlock2050683235, #ltBlock2050683635, #ltBlock2050683821, #ltBlock2050684152, #ltBlock2016446016, #ltBlock2016446034, #ltBlock2016446035, #ltBlock2054359068, #ltBlock2055000160, #ltBlock2055000163, #ltBlock2055000165, #ltBlock2055000174, #ltBlock2055000206, #ltBlock2055000208, #ltBlock2055000229, #ltBlock2055000232'); // ID формы виджета
	var cookie_max_age = 24 * 60 * 60; //Время жизни cookie в секундах.
	var delay = 1; //Задержка показа в миллисекундах, 1000 = 1 секунде.

	if (getCookie('popup_per_day') !== 'true') {
    	setTimeout(function() {


    	    if (chek.length == 0 && !window.location.href.includes('/widget/')) {
        	    if ($('.gc-main-content').hasClass('with-left-menu')) {
            	    $('.gc-main-content').append('<div class="info-banner menu"><a href="https://fitnessmama.school/plaska_link" target="_blank"><img class="img-responsive banner" src="https://fitnessmama.school/plaska"></a></div>');
            	} else {
                	$('.gc-main-content').append('<div class="info-banner"><a href="https://fitnessmama.school/plaska_link" target="_blank"><img class="img-responsive banner" src="https://fitnessmama.school/plaska"></a></div>');
            	}
        	} else {
            	console.log('на странице форма с ГК');

        	}

        	$('.info-banner').append('<div class="close-mybtn"></div>');
      		$('.close-mybtn').click(function() {
      	    $('.info-banner').hide();
       	    setCookie('popup_per_day', 'true', { 'max-age': cookie_max_age });
       	 });
   	 }, delay);
 	};
};


//FUNCTIONS
function getCookie(name) {
    var matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined;
}

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

    options = {
        path: '/',
            secure: true,
            // при необходимости добавьте другие значения по умолчанию
            ...options
    };

    if (options.expires instanceof Date) {
        options.expires = options.expires.toUTCString();
    }

    var updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);

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

    document.cookie = updatedCookie;
}
*/
//Гибкие права доступа -----------------------------------------------------------------------------


const sheetBaseUrl = 'https://docs.google.com/spreadsheets/d/1Cp0ymngh0kfGEgZ9UMkN5gxa4bSTxdw2I3bvBtJbZ3w/gviz/tq?tqx=out:csv';
const accessSheetUrl = sheetBaseUrl + '&sheet=Доступ';
const superUserSheetUrl = sheetBaseUrl + '&sheet=SUPERUSERS';

const currentPath = window.location.pathname.toLowerCase();
const userId = String(window.accountUserId).trim();

const waitForUserInfo = setInterval(() => {
    const user = window.userInfo;
    if (!user) return;
    clearInterval(waitForUserInfo);

    const hasAccessRole = user.isAdmin || user.isManager || user.isTeacher;
    if (!hasAccessRole) return;

    Promise.all([
        fetch(accessSheetUrl).then(r => r.text()),
        fetch(superUserSheetUrl).then(r => r.text())
    ])
        .then(([accessCsv, superCsv]) => {
            const superUsers = superCsv
                .trim()
                .split('\n')
                .flatMap(row => row.split(','))
                .map(id => id.replace(/["\r\n]/g, '').trim())
                .filter(Boolean);

            if (superUsers.includes(userId)) return;

            const rows = accessCsv.trim().split('\n'); // &#128072; теперь БЕЗ slice(1)
            const cleanRows = [];

            for (const row of rows) {
                const parts = row.split(',').map(p => p.replace(/["\r\n]/g, '').trim());
                const basePath = parts[1]?.toLowerCase() || "";
                const ids = parts.slice(2).filter(Boolean);

                if (basePath.length >= 3) {
                    cleanRows.push({basePath, ids});
                }
            }

            const matchedRow = cleanRows.find(r => currentPath.includes(r.basePath));

            if (matchedRow) {
                if (matchedRow.ids.includes(userId)) {
                    console.log(`&#9989; Доступ разрешён к "${matchedRow.basePath}"`);
                } else {
                    console.warn(`&#10060; Доступ запрещён — ID не найден в строке "${matchedRow.basePath}"`);
                    window.location.replace('/redirect-acces');
                }
            } else {
                console.log("&#11088; Путь не ограничен — доступ открыт");
            }
        })
        .catch(err => console.error('&#10060; Ошибка загрузки:', err));
}, 100);
