// Common script for public
'use strict';

// IE CustomEvent polifyl.
(function () {
    if (typeof window.CustomEvent === 'function') return false; //If not IE
  
    function CustomEvent(event, params) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent('CustomEvent');
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
        return evt;
    }
  
    CustomEvent.prototype = window.Event.prototype;
  
    window.CustomEvent = CustomEvent;
})();

window.switchProtocol = function(anchor){
    setTimeout(function() {
        if(window.location.protocol == 'http:'){
            var now = new Date();
            window.location.href = 'http://' + window.location.hostname + window.location.pathname + '?ts=' + now.getTime() + '#' + (anchor ? anchor : '');
        } else {
            window.location.reload();
        }
    }, 700);
}

jQuery(document).ready(function($){
// Global variables
    var $window = $(window),
        $body = $('body'),
        $search = $('#search');
// Search popups
    $('#search-button').on('click', function(e){
        e.preventDefault();
        // Displaying
        $search.addClass('is-visible');
        // Focusing in search input
        $('#search-input').focus();
        setTimeout(function(){
            $('.ya-site-form__input-text').focus();
        }, 1000);
        $body.addClass('no-scroll');
    });
    // Closing search
    $('.js-search-close').on('click', function(){
        $search.removeClass('is-visible');
        $body.removeClass('no-scroll');
    });
// Fixed header
    var $header = $('#header'),
        $usermenuBtn = $('.js-usermenu-action'),
        $usermenuList = $('.js-usermenu-list'),
        $main = $('.g-main');

    $('.js-site').on('click', '.js-usermenu-action', function(e){
        $('.js-usermenu-list').addClass('is-opened');
    });

    $usermenuBtn.on('click', function(e){
        e.stopPropagation();
        if($usermenuList.hasClass('is-opened')) {
            $usermenuList.removeClass('is-opened');
            return;
        }
        document.body.click();
        $usermenuList.addClass('is-opened');
        $window.click(function(){
            $usermenuList.removeClass('is-opened');
        });

        $header.on('click', function(){
            $usermenuList.removeClass('is-opened');
        })
    });
    $usermenuList.on('click', function(e){e.stopPropagation();});
    
// Alternative pull-out menu in public
    var $basemenu = $('.js-basemenu'),
        $basemenuClose = $('.js-basemenu-close'),
        $site = $('.js-site');

    $('.js-channel-burger').on('click', function(e){
        document.body.click();
        e.stopPropagation();
        if($basemenu.hasClass('is-visible')){ _hideMenu();return;}
        var userId = e.currentTarget.getAttribute('data-uid');
        if (!userId) { window.savedAction = function() { window.location.reload(); }; window.popup('signup'); return; }
        $basemenu.addClass('is-visible');
        $body.append('<div class="overlay overlay--light js-overlay"></div>');
        $basemenuClose.on('click', function(){_hideMenu();});
        $window.click(function(){_hideMenu();});
        
        function _hideMenu(){
            $basemenu.removeClass('is-visible');
            $('.js-overlay').remove();
        }
    });
    
// Pull-out menu in public
    var $navmenu = $('.js-navmenu'),
        $navmenuItem = $('.js-navmenu-item'),
        $navmenuCat = $('.js-navmenu-cat'),
        $navmenuClose = $('.js-navmenu-close'),
        $site = $('.js-site');

        
    $('body').on('click', '.js-header-burger', function(e){
        e.stopPropagation();
        $navmenu.addClass('is-visible');
        $window.click(hideNavmenu);
        $body
            .addClass('no-scroll')
            .append('<div class="overlay js-overlay" style="opacity: 0.6;"></div>');
    });

    $navmenuCat.on('click', function(e){
        var $target = $(e.target),
            $parent = $target.closest('.js-navmenu-item'),
            $inner = $parent.find('.js-navmenu-inner');

        e.preventDefault();
        if($parent.hasClass('is-opened')) {
            $parent.removeClass('is-opened');
            $inner.html('');
            return;
        };
        $inner.html('<ul class="navmenu__list"></ul>');

        var regex = /.+\/([0-9]+)\/.+/g,
            link = $target.prop('href'),
            id = link.replace(regex,'$1').st(),
            $list = $inner.children();

        $.getJSON('/home/xhr_subcat', { id: id }, function(res){
            $navmenuItem.removeClass('is-opened');
            $parent.addClass('is-opened');
            $.each(res, function(i, item){
                $list.append(
                    '<li class="navmenu__item">'+
                        '<a class="navmenu__link" href="/category/'+item.id+'/'+item.url+'">'+item.name+'</a>'+
                    '</li>'
                );
            });
        });
    });

    $navmenuClose.on('click', hideNavmenu);

    $navmenu.on('click', function(e){
        e.stopPropagation();
    });

    function hideNavmenu(){
        $navmenu.removeClass('is-visible');
        $body.removeClass('no-scroll');
        $site.removeAttr('style');
        $('.js-overlay').remove();
    }
// Dropdown with options
    var $propsmenuBtn = $('.js-propsmenu-btn'),
        $propsmenuLink = $('.js-propsmenu-link'),
        $propsmenuBody = $('.js-propsmenu-list');

    $propsmenuBtn.on('click', function(e){
        e.stopPropagation();
        if ($propsmenuBody.hasClass('is-opened')){
            $propsmenuBody.removeClass('is-opened');
            return;
        }
        $propsmenuBody.addClass('is-opened');
        $(window).click(function(){
            $propsmenuBody.removeClass('is-opened');
        });
    });

    $propsmenuLink.on('click', function(){
        $propsmenuBody.removeClass('is-opened');
    });

    $propsmenuBody.on('click', function(e){
        e.stopPropagation();
    });

// Scrolltop button
    var $scrollBtn = $('.js-scrolltop');

    $scrollBtn.on('click', function(e){
        e.preventDefault();
        $('html, body').animate({ scrollTop: 0 }, 'slow');
    });


// Window scroll handler
    $window.scroll(function(){
        if($window.scrollTop()>200){
            $scrollBtn.addClass('is-visible');
        }else{
            $scrollBtn.removeClass('is-visible');
        }
        if(window.isIE11) return;
        if(window.scrollY > ($header.outerHeight() + 50)){
            $header.attr('data-inverted', '');
        }else{
            $header.removeAttr('data-inverted');
        }
    });

// Tabs active
    (function(){
        if(window.isIE11) return;
        var tabItemSelector = '.js-kit-tabs-item',
            tabsItems = document.querySelectorAll(tabItemSelector),
            tabsHolder = document.querySelector('.js-kit-tabs-holder');
    
        tabsItems.forEach(function(el) {
            if(el.href === document.location.href){
                el.classList.add('is-active');
            }
        });

        var activeTab = document.querySelector(tabItemSelector+'.is-active');

        if(tabsHolder && activeTab){
            tabsHolder.scrollLeft = activeTab.getBoundingClientRect().left;
        }
    })();
});

jQuery(document).ready(function($){
    var $window = $(window),
        $body = $('body'),
        $content = $('#content'),
        $blockAtcions = $('.js-article-action');
    	
    if(false && $content.length){
        $window.resize(function(){
            $blockAtcions.css('width', $content.width());
        });

        $window.scroll(function(){
        	var maxDist = $content.offset().top + $content.height();
        	
            if($content.offset().top < $window.scrollTop() && maxDist > $window.scrollTop()){
                $blockAtcions.css('width', $content.width()).addClass('is-opened');
            }else{
                $blockAtcions.removeClass('is-opened');
            }
        });
    }
// Removing excess teasers
    var lastImg = $('#content .if:last');
    if(lastImg.length && lastImg[0].complete){
        __autocorrect();
    }else{
        lastImg.on('load',function(){
            __autocorrect();
        });
    }

    function __autocorrect(){
        var abHeight = $('#content').height(),
            sbHeight = $('.js-rightbar').height(),
            teasers  = $('.js-rightbar .js-tracker').get().reverse();
        if(sbHeight > abHeight){
            $.each(teasers, function(){
                if(sbHeight > abHeight){
                    $(this).hide(); sbHeight -=160;
                }
            });
        }
    }

// Sticky teasers
    var sidebar = $('.js-rightbar'),
        holderSticky = $('.js-sticky-holder'),
        itemSticky = $('.js-sticky-item'),
        copyItemSticky = itemSticky.clone();

    $window.on('resize scroll', function(){ 
        if(!$('.pagewrap').length || !$('.js-rightbar').length) return;

        var heightSidebar = sidebar.height() - 80,
            holderBn = $('.js-btn--right'),
            heightHolderBn = holderBn.height(),
            pagewrap = $('.pagewrap'),
            maxDistance = pagewrap.offset().top + pagewrap.height(),
            heightHolderBn = holderBn.height() || 0,
            topOffsetSidebar = sidebar.length ? sidebar.offset().top : null,
            freeSpace = _getSidebarAvailableArea(),
            activeArea = freeSpace > heightHolderBn ? freeSpace - heightHolderBn : freeSpace,
            tsrOffTop = freeSpace > heightHolderBn ? heightHolderBn+80 : 5,
            isBlockFixed = $window.scrollTop() > (heightSidebar+topOffsetSidebar),
            overScrolled = ($window.scrollTop() + heightHolderBn);
            
        setAmountTeasers(activeArea);
        
        if(isBlockFixed && !holderBn.length){
            holderSticky.addClass('is-filled');
        }else if(isBlockFixed && holderBn.length){
        	if(_getSidebarAvailableArea()-heightHolderBn > 0){
        		holderBn.addClass('is-fixed').css('top', 70);
        	}else{
        		holderBn.removeClass('is-fixed');
        	}
            holderSticky.addClass('is-filled').css('top', tsrOffTop);
        }else{
            holderBn.removeClass('is-fixed');
            holderSticky.removeClass('is-filled').removeClass('is-after');
        }
    });
    
    function _getSidebarAvailableArea(){
    // Local variables
    	var $window = $(window), pagewrap = $('.pagewrap');
    // Article page check
    	if(!window.location.href.match(/\/(news|article|post)\//)){
    		return $window.height();
    	}
    // Determing maximum distance and scrolled distance
    	var maxDistance = pagewrap.offset().top + pagewrap.height(),
    		scrollDist  = $window.scrollTop() + $window.height(),
    		difference  = maxDistance - scrollDist,
    		windHeight  = $window.height();
    // Returning available space
    	return difference>=0 ? windHeight-20 : windHeight + difference;
    }

    function setAmountTeasers(area){
        var countTeasers = Math.floor((area-30)/itemSticky.height());
        holderSticky.empty().hide();
        if(countTeasers > 0){
        	holderSticky.removeAttr('style');
            copyItemSticky.slice(-countTeasers).appendTo(holderSticky);
        }
    }

// Play YouTube video
    $body.on('click', '.js-video-thumb', function(){
        $(this).html('<iframe src="https://www.youtube.com/embed/'+
                     $(this).attr('data-id')+'?iv_load_policy=3&rel='+
                    '0&theme=dark&showinfo=0&autohide=1&autoplay=1" '+
                    'frameborder="0" allowfullscreen '+
                    'class="embed-responsive-item">&nbsp;</iframe>');
    });
// Activation Google Maps
    $('.image-map').on('click', function(){
        var $t = $(this),
            $wrap = $t.closest('.google-map');
        $wrap.css('height', '340px');
        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBGkE7oHleFSf0YxMy7ppPtQPgAsVy4U6M',
            dataType: 'script',
            success: function(){
                var coords = {
                    lat: $wrap.data('lat'),
                    lng: $wrap.data('lng')
                };

                var map = new google.maps.Map($t.closest('.google-map')[0], {
                    center: coords,
                    zoom: +$wrap.data('zoom') + 1,
                    mapTypeId: $wrap.data('type'),
                    mapTypeControl: false,
                    fullscreenControl: false,
                    streetViewControl: false
                });

                var marker = new google.maps.Marker({
                    position: coords,
                    map: map
                });
            }
        })
    });
});

jQuery(document).ready(function($){
// Check ab
    $('body').append('<ins class="adsbygoogle">&nbsp;</ins>');
    if($('.adsbygoogle:last').is(':visible')) window._planet_ = 'earth';
    $('.adsbygoogle:last').remove();
// Appending link to copied text
    document.oncopy = addLink;
// Checking AB
    var url = window.location.href ? window.location.href : document.URL,
        art = url.match(/\/(news|article|post)\//),
        act = window._planet_ ? 0:1,
        pat  = $('.isPA').length;
// Temporary Afox 980x120, 300x600, inArticle
    if($(window).width() >= 1000 && !window.mobilecheck()){
    	var adFoxInt = setInterval(function(){
    		if(window.hasOwnProperty("Ya") && typeof window.Ya !== 'undefined' && window.Ya.hasOwnProperty("adfoxCode") && typeof window.Ya.adfoxCode !== 'undefined'){
    	    // 980x200
    			if($('#adfox_15898003027192864').length)
			    window.Ya.adfoxCode.create({ownerId:264496,containerId:"adfox_15898003027192864",params:{p1:"ckqrw",p2:"gveb"}});
			// 300x600 // url.match(/\/(article)\/476734/)
			    if($('#adfox_158980032888054642').length)
			    window.Ya.adfoxCode.create({ownerId:264496,containerId:"adfox_158980032888054642",params:{p1:"ckqgp",p2:"gvea"}});
			// Intext video - huggies
			    if($('#adfox_159343809871389555').length)
			    window.Ya.adfoxCode.create({ownerId:264496,containerId:"adfox_159343809871389555",params:{p1:"clgmh",p2:"gwjh",insertAfter:"undefined",insertPosition:"0",stick:!1,stickTo:"auto",stickyColorScheme:"light"},onRender:function(){var i=0,o=setInterval(function(e,t,n){n=(t=document.getElementById("adfox_159343809871389555")).parentNode.querySelectorAll("#gc_containerId21049, #yandex_rtb_R-A-70350-39, ins, .sjfirst, .intext-left, .intext-right"),90<t.clientHeight&&[].forEach.call(n,function(e){e.style.display="none"}),(250<++i||90<t.clientHeight)&&clearInterval(o)},100)}});	
			// Intext video - terracreativa
			    if($('#adfox_16001076031685542').length)
			    window.Ya.adfoxCode.create({ownerId:264496,containerId:"adfox_16001076031685542",params:{p1:"cmiqe",p2:"gwjh",insertAfter:void 0,insertPosition:"0",stick:!1,stickTo:"auto",stickyColorScheme:"light"},onRender:function(){var i=0,o=setInterval(function(e,t,n){n=(t=document.getElementById("adfox_16001076031685542")).parentNode.querySelectorAll("#gc_containerId21049, #yandex_rtb_R-A-70350-39, ins, .sjfirst, .intext-left, .intext-right"),90<t.clientHeight&&[].forEach.call(n,function(e){e.style.display="none"}),(250<++i||90<t.clientHeight)&&clearInterval(o)},100)}});
			// Intext video - terracreativa
			    if($('#adfox_160022384042032249').length)
			    window.Ya.adfoxCode.create({ownerId:264496,containerId:"adfox_160022384042032249",params:{p1:"cmjgs",p2:"gwjh",insertAfter:void 0,insertPosition:"0",stick:!1,stickTo:"auto",stickyColorScheme:"light"},onRender:function(){var i=0,o=setInterval(function(e,t,n){n=(t=document.getElementById("adfox_160022384042032249")).parentNode.querySelectorAll("#gc_containerId21049, #yandex_rtb_R-A-70350-39, ins, .sjfirst, .intext-left, .intext-right"),90<t.clientHeight&&[].forEach.call(n,function(e){e.style.display="none"}),(250<++i||90<t.clientHeight)&&clearInterval(o)},100)}});	
			// Clearing interval
    			clearInterval(adFoxInt);
    		}
    	}, 500);
    }
// Getting new blocks
    if(act && art){
        if(url.match(/\/article\//)){
            $.post('/article/xhr_adjust_block', {url:url}, function(data){
                if(!data) return false;
            // Distributing new blocks
                $('.intext').each(function(i, v){
                    $(this).after('<div class="intext">'+data[i]+'</div>');
                    $(this).hide();
                });
            });
        }else{
            $('.feature--inner').addClass('feature--inline').removeClass('feature--inner');
            $('.intext-left').addClass('intext-inline').removeClass('intext-left').width('100%');
        }
    }
// Hide top banner on video display
    if(url.match(/\/article\//)){
        window.check_mv_interval = 0;
        var check_mv = setInterval(function(){
            window.check_mv_interval += 100;
            var cont = $('#yandex_top'),
                ad = cont.children('yatag'),
                mv = $('#moevid').height();
            if(mv > 100) cont.remove();
            if(window.check_mv_interval > 10000 || mv > 100){
                clearInterval(check_mv);
            }
        },100);
    }
// NativeScope
    initNativeScope(); 
// SlickJump
    //if(pat && url.match(/\/article\//) && !window.mobilecheck()){ // $('#mc133').length
    if(url.match(/\/(article)\//)){
        var mcid = $('.js-mcat').attr('id'),
            mcid = mcid ? parseInt($('.js-mcat').attr('id').replace(/[^0-9]/g,'')):0,
            mcsl = [167, 133, 178, 30, 268, 246, 288, 116].indexOf(mcid) !== -1;
        if(pat && !window.mobilecheck()){ // && mcsl
            initSlickjump();
        }
    }
// Ttarget mob
    if(document.URL.match(/\/article\/394987\//)){}
    else if(url.match(/\/article\//) && window._planet_ && window.mobilecheck()){
        initTargetMob();
    }
// Video Play
    if(url.match(/\/article\//) && window._planet_ && !window.mobilecheck()){
        //setTimeout(function(){check_video(0)}, 100);
    }
// GM
    initGM();
// Videonow
    if(document.URL.match(/\/article\/394987\//) && !window.mobilecheck()) initVideoNow();
    else if(url.match(/\/article\//) && window._planet_ && !window.mobilecheck()){
        initInPage();
        setTimeout(function(){initVideoNow()},4000);
    // Hiding default ads
        setTimeout(function(){
            var vidTO = setInterval(function(){
            	var vidCNT=0,
	                inpage = $('#inpage'),
	                vidnow = $('#vdnow, .vn-player'),
	                sjcont = $('#sjcont'),
	                adblck = $('.intext').eq(1);
            // Checking video blocks
                if(inpage.length && inpage.height()>10){
                    vidnow.html('').hide(); adblck.hide();
                    if(!!sjcont) sjcont.hide();
                }
                else if(vidnow.length && vidnow.height()>10){
                    inpage.hide(); adblck.hide();
                    if(!!sjcont) sjcont.hide();
                }
            // Breaking sequence
                if(++vidCNT > 300) clearInterval(vidTO);
            }, 100);
        }, 500);
    }
// Native rent
    initNativeRent();
// Astraone
    gip();
// 24SMI
//    init24smi();
});

var inits = [];

function check_video(wait){
// Loops
    if(wait >= 20) return false;
// Vars
    var yb = document.querySelector('#yandex_top .yap-rtb__wrapper'),
        ww = !!yb ? yb.offsetWidth : 0,
        wh = !!yb ? yb.offsetHeight : 0;
// Sequence
    if(ww != 600 || (wh != 5 && wh != 6)){
        setTimeout(function(){
            check_video(++wait);
        }, 500);
    }else if(document.URL.match(/\/article\//)){
            initVideoPlay();
    }
}

function initCheck(v){
    return -1!=inits.indexOf(v)||inits.length>2;
}

function initNativeRent(){
// Checking article to skip
if(!document.URL.match(/\/article\//)) return;
//if(!$('#sc118').length) return;
// Vars
	var dmt  = document,
		cnt1 = dmt.createElement('div'),
		cnt2 = dmt.createElement('div'),
		cnt3 = dmt.createElement('div'),
	    trg1 = dmt.getElementsByClassName('intext')[0],
	    trg2 = dmt.getElementsByClassName('intext')[1],
	    trg3 = dmt.getElementById('yandex_flat');
// Chaning third container for mobile devices
	if(!trg3) trg3 = dmt.getElementsByClassName('intext')[1];
// Adding IDs
    cnt1.id = 'NRent-5ced10a04aa78-2';
    cnt2.id = 'NRent-5ced10a04aa78-3';
    cnt3.id = 'NRent-5ced10a04aa78-4';
// Adding containers
	if(trg1) trg1.parentNode.insertBefore(cnt1, trg1.nextSibling);
	if(trg2) trg2.parentNode.insertBefore(cnt2, trg2.nextSibling);
	if(trg3) trg3.parentNode.insertBefore(cnt3, trg3.nextSibling);
// Code invoking
    (function(){
    	if(trg1){
	        (window.NRentManager = window.NRentManager || []).push({
	            renderTo: "NRent-5ced10a04aa78-2",
	            position: "horizontalTop",
	            verbose: true,
	            onRender: function(){},
	            onStub: function(){}
	        });
        }
    	if(trg2){
	        (window.NRentManager = window.NRentManager || []).push({
	            renderTo: "NRent-5ced10a04aa78-3",
	            position: "horizontalMiddle",
	            verbose: true,
	            onRender: function(){},
	            onStub: function(){}
	        });
        }
        if(trg3){
	        (window.NRentManager = window.NRentManager || []).push({
	            renderTo: "NRent-5ced10a04aa78-4",
	            position: "horizontalBottom",
	            verbose: true,
		        onRender: function(){},
		        onStub: function(){}
	        });
        }
    }());
}

function initInPage(){
// Checking article to skip
    if(document.URL.match(/\/article\/434647\//)) return;
// Vars
	var dmt = document,
	    idf = 'inpage',
	    trg = dmt.getElementsByClassName('intext')[1],
	    cnt = dmt.createElement('div');
// Launch checks
    if(window.mobilecheck() || !!!trg || initCheck(idf)) return;
// Marking launched
    cnt.id = idf;
    inits.push(idf);
    trg.parentNode.insertBefore(cnt, trg);
// Library
    (function(w, d, n, s, t){
        w[n] = w[n] || [];
        w[n].push(function(){
            Ya.Context.AdvManager.render({
                blockId: 'VI-181070-0', // VI-188293-0
                renderTo: idf,
                inpage: {startupTimeout:1},
            }, function callback(params){
                params.onAdStart = function(at){
                    trg.innerHTML='';
                    console.log('INPAGE: START');
                    window.inpageStarted = 1;
                };
                params.onAdEnd = function(at){};
            });
        });
        t = d.getElementsByTagName("script")[0];
        s = d.createElement("script");
        s.type = "text/javascript";
        s.src = "//an.yandex.ru/system/context.js";
        s.async = true;
        t.parentNode.insertBefore(s, t);
    })(window, document, "yandexContextAsyncCallbacks");
}

function initVideoNow(){
// Checking article to skip
    if(document.URL.match(/\/article\/434647\//)) return;
// Checking article
if(window.inpageStarted) return console.log('VDN STOPPED');
// Vars
var dmt = document,
    trg = dmt.getElementsByClassName('intext')[1],
    cnt = dmt.createElement('div'),
    prt = dmt.location.protocol === 'https:' ? 'https:' :'http:'
    url = prt+'//static.videonow.ru/vn_init.js?profileId=3232979';
// Launch checks
    if(!cnt || !trg) return;
// Marking launched
    cnt.className = 'vdnow';
    cnt.id = 'vdnow';
    trg.parentNode.insertBefore(cnt, trg);
    inits.push('videonow');
// Library
    (function(){
        var mvads = document.createElement("script");
            mvads.async = true;
            mvads.type = "text/javascript";
            mvads.src = url;
        var node = document.getElementsByTagName("head")[0];
            node.appendChild(mvads, node);
    })();
}

function gip(){
// Checking article to skip
	if(!document.URL.match(/\/(news|article|post)\//)) return;
    if(document.URL.match(/\/article\/373988\//)) return;
// Vars
var dmt = document,
    trg = dmt.getElementsByClassName('photo')[0];
// Launch checks
    if(!trg) return;
// Setting attribute
	trg.setAttribute("data-afp-iib", "5eb583217bc72fbda0f532f0");
// Code...
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.async = true;
    s.src = "https://cdn.afp.ai/ssp/sdk.js";
    (document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0]).appendChild(s);
// Code...
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.async = true;
    s.src = "https://cdn.afp.ai/ssp/sdk_review.js";
    (document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0]).appendChild(s);
}

function initGM(){
// Checking article to skip
    if(!document.URL.match(/\/(news|article|post)\//)) return;
// Vars
    var dmt = document,
        idf = 'gmedia',
        trg = dmt.getElementsByClassName('intext')[2],
        cnt = dmt.createElement('div');
    cnt.id = idf;
// Launch checks
    if(window.mobilecheck() || !!!trg || initCheck(idf)) return;
// Marking launched
    cnt.id = idf;
    inits.push(idf);
    trg.parentNode.insertBefore(cnt, trg);
// Code...
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.async = true;
    s.src = "https://inplayer.ru/player/in-player-test.js";
    (document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0]).appendChild(s);
// Conf vars
    s.onload = function(){
        var videoplayer = new INPlayer({
            id: 'gmedia',
            skin: 'https://inplayer.ru/player/skin/basic/in-player-skin.css',
            pid: 841,
            vr: {
                'preroll': 1
            },
            logo: false,
            sharing: false,
            width: '',
            height: '',
            playlist: true,
            "playlistLink":"https://cdn.sova.ru.net/export-videos.json?section=11",
            autoPlay: true,
            autoPlayView: true,
            autoPlayContent: false,
            flyscreen: false,
            flyscreenAlign: "right",
            iabid: '52',
            hidePreloader: false,
        });
    };
// Checking if loaded
    var gmST = 0;
    var gmTO = setInterval(function(){
    // Getting gm block
        var gzb =  dmt.getElementById('gmBlock');
    // Checking video blocks
        if(gzb.length && gzb.height()>10){
            trg.remove();
        }
    // Breaking sequence
        if(++gmST > 300) clearInterval(vidTO);
    }, 1000);
}

function initTargetMob(){
// Vars
    var elm = document.querySelectorAll('.intext'),
        div = document.createElement('div');
// Launch checks
    if(!window.mobilecheck() || !!!elm[2] || initCheck('targetmob')) return;
// Settings
    div.dataset.widget = 'tiDOPNLSKFtEpsFu';
    elm[2].parentNode.insertBefore(div, elm[2]);
// Library
    (function(b,c){
        c.id=b.querySelector('div[data-widget="tiDOPNLSKFtEpsFu"]');
        var a=b.createElement("script");a.src="//tt.ttarget.ru/s/tt3.js?v=2";
        a.async=!0;
        a.onload=a.readystatechange=function(){
            a.readyState&&"loaded"!=a.readyState&&"complete"!=a.readyState||(a.onload=a.readystatechange=null,TT.createBlock(c))
        };
        b.getElementsByTagName("head")[0].appendChild(a)
    })(document,{block:1861,count:0});
}

function initTargetDsk(){
// Vars
    var vcnt = document.getElementById('ttarg'),
        ycnt = document.getElementById('yandex_top'),
        vdiv = document.createElement('div');
// Launch checks
    if(window.mobilecheck() || !!!vcnt || initCheck('targetdsk')) return;
// Settings
    vdiv.dataset.widget = 'TOJTIeOfTJjLems9';
    vcnt.setAttribute('style', 'overflow:hidden');
    vcnt.appendChild(vdiv); ycnt.remove();
// Library
    (function(b,c){
        c.id=b.querySelector('div[data-widget="TOJTIeOfTJjLems9"]');
        var a=b.createElement("script");
            a.src="//tt.ttarget.ru/s/tt3.js?v=2";
            a.async=!0;
            a.onload=a.readystatechange=function(){
                a.readyState&&"loaded"!=a.readyState&&"complete"!=a.readyState||(a.onload=a.readystatechange=null,TT.createBlock(c))
            };
            b.getElementsByTagName("head")[0].appendChild(a)
    })(document,{block: 1889, count: 4});
// Callbacks
    document.addEventListener('tt.video.close', function (event) {
        initVideoPlay();
    });
    document.addEventListener('tt.block.noAd', function (event) {
        initVideoPlay();
    });
}

function initVideoPlay(){
// Checking article to skip
    if(document.URL.match(/\/article\/434647\//)) return;
// Launch checks
    if(window.mobilecheck() || initCheck('vidplay') || !inits.push('vidplay')) return;
// Frame html
    var frame = '<div id="vidplay"><iframe width="728" height="320" frameborder="0" scrolling="no" allowfullscreen="true" '
                +'src="//fb.ru/misc/temp/videonow.html"></iframe></div>';
    $('.pagewrap').prepend(frame);
    setTimeout(function(){$('#vidplay').remove()},80000);
}

function initNativeScope(){
// Checking article to skip
    if(document.URL.match(/\/article\/462884\//)) return;
// Checking for at least 1 blocks on pay
    if($('.intext').length < 1) return;
// Adding id to first block
    $('.intext:first').prop('id', 'containerId21049');
// Initiating library
	(function(w, d, c, s, t){
		w[c] = w[c] || [];
		w[c].push(function(){
			gnezdo.create({
				tizerId: 21049,
				containerId: 'containerId21049',
				onSuccess: function(b){
					$('.intext:first').html('');
					window.hasNS1 = true;
				},
				onEmpty: function(b){console.log('onEmpty.')}
			});
		});
        t = d.getElementsByTagName("script")[0];
        s = d.createElement("script");
        s.type = "text/javascript";
        s.src = "//news.2xclick.ru/loader.js";
        s.async = true;
        t.parentNode.insertBefore(s, t);
	})(window, document, 'gnezdoAsyncCallbacks');
}

function initSlickjump(){
	if($('#adfox_16001076031685542').length) return false;
	if($('#adfox_159343809871389555').length) return false;
	if($('#adfox_160022384042032249').length) return false;
// Checking article to skip
    if(document.URL.match(/\/article\/462884\//)) return;
// Checking for at least 1 blocks on pay
    if($('.intext').length < 1) return;
// Loading script
    var script = document.createElement("script");
        script.async = true;
        script.setAttribute("site", "2kw2bxtrzbmiva5g03k");
        script.type = "text/javascript",
        script.src = '//sjsmartcontent.org/static/plugin-site/js/sjplugin.js';
    var node = document.getElementsByTagName("head")[0];
        node.appendChild(script, node);
    var firstB = $('.intext').eq(0),
        secndB = $('.intext').eq(1),
        thirdB = $('.intext').eq(2);
// First block container
    if($('.intext > ins').length && !firstB.hasClass('af') && !window.hasNS1){
        firstB.before('<div class="sjfirst"><sjdiv id="SlickJumpNativeAds-cuiwcdj54"></sjdiv></div>');
    }
// Second block container
    if($('.intext > ins').length > 1 && !secndB.hasClass('af')){
        secndB.before('<div id="sjcont"><sjdiv id="SlickJumpNativeAds-sm00vk"></sjdiv></div>');
    }
// Second block container
    if($('.intext > ins').length > 2 && !thirdB.hasClass('af')){
        thirdB.before('<div><sjdiv id="SlickJumpNativeAds-sm01vj"></sjdiv></div>');
    }
// Hiding default ads
    setTimeout(function(){
        var sjCNT=0, sjTO = setInterval(function(){
            var first = $('#SlickJumpNativeAds-cuiwcdj54'),
                secnd = $('#SlickJumpNativeAds-sm00vk'),
                third = $('#SlickJumpNativeAds-sm01vj');
            if(first.parent().height()>10){
                var gad = first.parent('div').next('.intext');
                if(gad.hasClass('intext')) gad.html('');
            }
            if(secnd.parent().height()>10){
                var gad = secnd.parent('div').nextAll('.intext').eq(0);
                if(gad.hasClass('intext')) gad.html('');
            }
            if(third.parent().height()>10){
                var gad = third.parent('div').nextAll('.intext').eq(0);
                if(gad.hasClass('intext')) gad.html('');
            }
            if(++sjCNT>50)clearInterval(sjTO);
        },100);
    }, 500);
}

document.addEventListener('channelcomplete', initChannelsAds);

function initChannelsAds(){ 
// Switching off for desktops
//	if(!window.mobilecheck()) return channelVdNow();
// Defining variables
    var yndxCntID = 'M468788ScriptRootC767175', //Math.random().toString(36).replace(/[^a-z]/g,''),
    	targetElm, blockId, dmt = document, ins, gadPubID, gadSlotID,
        container  = dmt.createElement('div'),
        fullScrDiv = dmt.createElement('div'),
        targetElm = dmt.getElementById('channel_page_comment_block'),
        utmSrcFB = document.URL.match('=fb');
// Setting container class
  	container.id = yndxCntID;
  	container.style.cssText = "width:100%;background:#EEE;margin:0 auto 15px"; 
// Device specific vars
  	if(window.mobilecheck()){
  		blockId = "R-A-70350-107";
  		gadPubID = "ca-pub-2357891147905917";
  		gadSlotID = "8335025132";
    // Adfox fullscreen
  		if(!utmSrcFB && typeof window.Ya != 'undefined' && typeof window.Ya.adfoxCode != 'undefined'){
	  		fullScrDiv.id = "adfox_156332333077593985";
	  		dmt.body.appendChild(fullScrDiv);
		    window.Ya.adfoxCode.create({
		        ownerId: 264496,
		        containerId: 'adfox_156332333077593985',
		        params: {pp:'ngx', ps:'djis', p2:'glma'}
		    });
  		}
  	}else{
  		blockId = "R-A-70350-109", 
  		gadPubID = "ca-pub-0498930789498528";
  		gadSlotID = "1811292462";
  	}
// Adding elements
    targetElm.parentNode.insertBefore(container, targetElm);
// Loading yandex direct
    (function(w, d, n, s, t) {
        w[n] = w[n] || [];
        w[n].push(function() {
            Ya.Context.AdvManager.render({
                blockId: blockId,
                renderTo: yndxCntID,
                statId: 70350,
                async: true,
            },
            function altCallback(){
            	_loadZenWidget();
        	});
        });
        
        _loadSript('//an.yandex.ru/system/context.js');
        
		function _loadSript(url, callback){
	        t = d.getElementsByTagName("script")[0];
	        s = d.createElement("script");
	        s.type = "text/javascript";
	        s.src = url;
	        s.async = true;
	        t.parentNode.insertBefore(s, t);
	        if(callback) s.onload = callback;
	        if(!url.match('widget')) s.onerror = function(){
	        	_loadZenWidget();
	        }
		}
        
        function _loadZenWidget(){
        	w['yandexZenAsyncCallbacks'] = [];
	        w['yandexZenAsyncCallbacks'].push(function(){
	            w.YandexZen.renderWidget({
	                clid: [894,895],
	                container: '#'+yndxCntID,
	                orientation: 'horizontal',
	                size: 'l',
	               failCallback:function(){
	            	    container.style.cssText = "width:100%;margin:0 auto 15px"; 
				        (function(){
				        	var d = ((d = new Date()) ? '' + d.getUTCFullYear() + d.getUTCMonth() + d.getUTCDate() + d.getUTCHours() : '');
				        	_loadSript("//jsc.lentainform.com/f/b/fb.ru.767175.js?t="+d);
        				})();
	               },
	            });
	        });
        	_loadSript("//zen.yandex.ru/widget-loader");
        }
        
        function _loadZenWidget2(){
        	var cnt = document.createElement('div'),
        		trg = document.getElementById('channel-page-feed');
        	cnt.id = 'zWidCnt';
        	cnt.style.cssText = "margin:-15px 0 0";
		// Adding elements
		    trg.parentNode.insertBefore(cnt, trg);
        	
        	w['yandexZenAsyncCallbacks'] = [];
	        w['yandexZenAsyncCallbacks'].push(function(){
	            w.YandexZen.renderWidget({
	                clid: [894,895],
	                container: '#zWidCnt',
	                orientation: 'horizontal',
	                size: 'l', 
	            });
	        });
        	_loadSript("//zen.yandex.ru/widget-loader");
        }
		
        function _loadGA(){
        	if(/firefox/i.test(navigator.userAgent)) return;
        	_loadSript('//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', function(){
        		ins = document.createElement("ins");
        		ins.setAttribute('class','adsbygoogle');
				ins.setAttribute('style','display:block;');
				ins.setAttribute('data-ad-client', gadPubID);
				ins.setAttribute('data-ad-slot', gadSlotID);
				ins.setAttribute('data-ad-format','auto');
				ins.setAttribute('data-full-width-responsive', true);
        		container.innerHTML = ins.outerHTML;
        		(adsbygoogle = window.adsbygoogle || []).push({});
        	});
        }
        
    })(window, document, "yandexContextAsyncCallbacks");
}

function channelVdNow(){
// Checking article to skip
    if(!document.URL.match(/\/c\/noneeee/)) return;
// Library
    $('body').on('click', '.grablink__img', function(e){
	    (function(){
	        var mvads = document.createElement("script");
	            mvads.async = true;
	            mvads.type = "text/javascript";
	            mvads.src = '//moe.video/js/replacer.js';
	        var node = document.getElementsByTagName("head")[0];
	            node.appendChild(mvads, node);
	        mvads.onload = function(){
	        	MoeVideo.Wrapper({'pin':'36880451'});
	        }
	    })();
    });
}

//document.addEventListener('channelcomplete', initLimitChannelCmt);

function initLimitChannelCmt(){
	if($('#channel_page_comment_list').length){
		var chCmt = $('#channel_page_comment_list').find('.discuss__item'), i;
		for(i=1; i<5; i++) chCmt.eq(i).hide();
	}
}

function init24smi(){
// Vars
	var dmt = document,
		nws = window.location.href.match(/\/(news|post)\//),
	    trg = dmt.getElementsByClassName('intext-left')[0];
// Check
	if(!!!trg || window.mobilecheck() || !nws) return;
// Setting ID
	trg.id = 'smi_teaser_12686';
// Library
	 (function(){
		 var sm = document.createElement("script");
		 sm.type = "text/javascript";
		 sm.async = true;
		 sm.src = "//jsn.24smi.net/1/d/12686.js";
		 var s = document.getElementsByTagName("script")[0];
		 s.parentNode.insertBefore(sm, s);
	 })();
}

function addLink(){
// Checking article to skip
    if(document.URL.match(/\/c\//)) return;
// Appending link
    var d = document, w = window,
        elt = d.getElementById('content'),
        sel = w.getSelection(),
        url = d.location.href,
        pgl = " - Читайте подробнее на FB.ru: <a href='"+url+"'>"+url+"</a>",
        cpt = sel + pgl,
        div = d.createElement('div');
    div.style.position='absolute';
    div.style.left='-99999px';
    elt.appendChild(div);
    div.innerHTML = cpt;
    sel.selectAllChildren(div);
    w.setTimeout(function() {
        elt.removeChild(div);
    },0);
}

window.mobilecheck = function(){
  var check = false;
  (function(a){if(/(iPad|iPod|android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
}
