$(document).ready(function () {

    $('.broadcast-close').click(function () {
        $('.broadcast').addClass('hidden-block');
    })

    $('.header-top input')
        .focus(
            function(){
                $('.header-top form').addClass('show-bg');
            })
        .blur(
            function(){
                $('.header-top form').removeClass('show-bg');
            });

    /*sliders*/
    let time = 1,
    time2 = 1;
    let $bar,
        isPause,
        isPause2,
        tick,
        tick2,
        percentTime,
        percentTime2;

    let bannerSlide = $('.home-page-banner-slider');
    bannerSlide.slick({
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: false,
        swipe: false,
        dots: true,
        responsive: [
            {
                breakpoint: 991.98,
                settings: {
                    swipe: true
                }
            }
        ]
    });

    let shortNewsSlide = $('.short-news-slider');
    shortNewsSlide.slick({
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: true,
        swipe: false,
        dots: true
    });

    $('.home-page-media-slider').slick({
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: true,
        autoplay: true,
        autoplaySpeed: 4000
    });

    $('.poster-slider').slick({
        infinite: true,
        slidesToShow: 4,
        slidesToScroll: 1,
        responsive: [
            {
                breakpoint: 991.98,
                settings: {
                    slidesToShow: 3
                }
            },
            {
                breakpoint: 767.98,
                settings: {
                    slidesToShow: 2,
                    centerMode: true,
                    centerPadding: 5
                }
            },
            {
                breakpoint: 460.98,
                settings: {
                    slidesToShow: 1
                }
            }
        ]
    });

    $('.home-page-media-adaptive-slider').slick({
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 4000
    });

    $('.home-page-cinema-slider').slick({
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 4000,
        responsive: [
            {
                breakpoint: 767.98,
                settings: {
                    slidesToShow: 1,
                    centerMode: true,
                    centerPadding: 5
                }
            }
        ]
    });

		$('.cinemas-slider').slick({
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: false,
        autoplaySpeed: 4000,
        responsive: [
            {
                breakpoint: 767.98,
                settings: {
                    slidesToShow: 1,
                    centerMode: true,
                    centerPadding: 5
                }
            }
        ]
    });


    $('.single-news-page-slider-first').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: true,
        fade: true,
        infinite: true,
    });

    $('.single-news-page-slider-second').slick({
        slidesToShow: 4,
        slidesToScroll: 1,
        asNavFor: '.single-news-page-slider-first',
        dots: false,
        infinite: true,
        centerMode: true,
        focusOnSelect: true
    });

    $(window).resize(function(){
        $('.single-news-page-slider-first')[0].slick.refresh();
        $('.single-news-page-slider-second')[0].slick.refresh();
    });

    /*banner slider progressbar*/

    $bar = $('.slider-progress .progress');

    function startProgressbar() {
        resetProgressbar();
        percentTime = 0;
        isPause = false;
        tick = setInterval(interval, 60); // N секунд * 10
    }

    function interval() {
        if (isPause === false) {
            percentTime += 1 / (time + 0.1);
            $bar.css({
                width: percentTime + "%"
            });
            if (percentTime >= 100) {
                bannerSlide.slick('slickNext');
                startProgressbar();
            }
        }
    }

    function resetProgressbar() {
        $bar.css({
            width: 0 + '%'
        });
        clearTimeout(tick);
    }

    startProgressbar();

    $('.home-page-banner .slick-next, .home-page-banner .slick-prev, .home-page-banner .slick-dots li').click(function() {
        startProgressbar();
    });

    let adaptiveSlider = window.matchMedia('(max-width: 991.98px)');
    if (adaptiveSlider.matches) {
        bannerSlide.on('swipe', function(){
            startProgressbar();
        });
    }

    /*shortnews slider progressbar*/

    let shortNewsProgressBar = $('.short-news-slider-progress .progress');

    function startProgressbar2() {
        resetProgressbar2();
        percentTime2 = 0;
        isPause2 = false;
        tick2 = setInterval(interval2, 100);
    }

    function interval2() {
        if (isPause2 === false) {
            percentTime2 += 1 / (time2 + 0.1);
            shortNewsProgressBar.css({
                width: percentTime2 + "%"
            });
            if (percentTime2 >= 100) {
                shortNewsSlide.slick('slickNext');
                startProgressbar2();
            }
        }
    }

    function resetProgressbar2() {
        shortNewsProgressBar.css({
            width: 0 + '%'
        });
        clearTimeout(tick2);
    }

    startProgressbar2();

    $('.home-page-short-news .slick-next, .home-page-short-news .slick-prev, .home-page-short-news .slick-dots li').click(function() {
        startProgressbar2();
    });

    /*sidebar*/

    setTimeout(function () {
        $('.home-page-sidebar-top').removeClass('show-weather')
    }, 5000);

    $('.home-page-sidebar-top').hover(
        function() {
            $('.weather').hover(
                function () {
                    $('.home-page-sidebar-top').addClass('show-weather')
                }
            )
        },
        function() {
            $('.home-page-sidebar-top').removeClass('show-weather')
        }
    );

    $('.newspaper-download-btn button').hover(
        function () {
            $('.newspaper-download-btn p').removeClass('hidden-block')
        },
        function () {
            $('.newspaper-download-btn p').addClass('hidden-block')
        }
    )

    $('.sidebar-nav-link, .other-sections').hover(
        function () {
            $(this).addClass('sidebar-nav-submenu-active')
        },
        function () {
            $(this).removeClass('sidebar-nav-submenu-active')
        }
    )

    $('.sidebar-nav-link').each(function() {
        if (!($(this).find('.sidebar-nav-submenu').length)) {
            $(this).addClass('sidebar-without-submenu')
        }
    });

    if ($('.sidebar-nav-link').length > 9) {
        $('.home-page-sidebar').addClass('sidebar-nav-big')
    }

    /*fancybox*/

    $(".fancybox-video").click(function () {
        $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : this.title,
            'width'         : 680,
            'height'        : 495,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'          : 'swf',
            'swf'           : {
                'wmode'        : 'transparent',
                'allowfullscreen'   : 'true'
            }
        });
        return false;
    })

    $(".fancybox-adaptive-video").click(function () {
        $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'height'        : '350px',
            'title'         : this.title,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'          : 'swf',
            'swf'           : {
                'wmode'        : 'transparent',
                'allowfullscreen'   : 'true'
            }
        });
        return false;
    })

    /*news img*/

    $('.home-page-news-1, .news-container').each(function() {
        if (!($(this).find('img').length)) {
            $(this).addClass('news-without-img')
            $('.news-without-img .home-page-news-1-img').addClass('hidden-block')
            $('.news-without-img .news-container-img').addClass('hidden-block')

        }
        else (
            $(this).addClass('news-with-img')
        )
    });
/*
    $(".home-page-news-1 .news-with-img h5").text(function (i, text) {
        if (text.length >= 56) {
            text = text.substring(0, 55);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    $(".news-container.news-with-img h5").text(function (i, text) {
        if (text.length >= 54) {
            text = text.substring(0, 54);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    $(".home-page-news-3 h5").text(function (i, text) {
        if (text.length >= 90) {
            text = text.substring(0, 90);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    $(".short-news-left h5").text(function (i, text) {
        if (text.length >= 80) {
            text = text.substring(0, 80);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    $(".home-page-media-slider-big h5").text(function (i, text) {
        if (text.length >= 100) {
            text = text.substring(0, 100);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    $(".home-page-media-slider-small h5").text(function (i, text) {
        if (text.length >= 56) {
            text = text.substring(0, 55);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    $(".news-page-short-news-content h5, .home-page-news-1-text h5").text(function (i, text) {
        if (text.length >= 80) {
            text = text.substring(0, 80);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...' ; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    $(".media-adaptive-slide-container h5").text(function (i, text) {
        if (text.length >= 100) {
            text = text.substring(0, 100);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    $(".cinema-text > p").text(function (i, text) {
        if (text.length >= 360) {
            text = text.substring(0, 360);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

    //if (window.matchMedia("(max-width: 575.98px)").matches) {
        $(".news-without-img h5, .short-news h5, .news-page-short-news-content h5").text(function (i, text) {
            if (text.length >= 70) {
                text = text.substring(0, 70);
                let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
                text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
            }
            $(this).text(text);
        })
    //}

    $(".page-newspaper-themes-right h5").text(function (i, text) {
        if (text.length >= 35) {
            text = text.substring(0, 35);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })
    $(".page-newspaper .newspaper-bottom-news-content-text h5").text(function (i, text) {
        if (text.length >= 65) {
            text = text.substring(0, 65);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })
    $(".page-newspaper .page-newspaper-themes-left h5").text(function (i, text) {
        if (text.length >= 80) {
            text = text.substring(0, 80);
            let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
            text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
        }
        $(this).text(text);
    })

   if (window.matchMedia("(max-width: 767.98px)").matches) {
        $(".page-newspaper .only-title .home-page-news-1-text h5").text(function (i, text) {
            if (text.length >= 80) {
                text = text.substring(0, 80);
                let lastIndex = text.lastIndexOf(" ");       // позиция последнего пробела
                text = text.substring(0, lastIndex) + '...'; // обрезаем до последнего слова
            }
            $(this).text(text);
        })
    }*/

    /*modal*/

    $('.close-menu').click(function () {
        event.preventDefault()
        $('#openMenu').modal('hide')
   });

    $('.open-menu-modal button').click(function () {
        $('#openMenu').modal('hide')
   })

    /*adaptive menu*/

    $('.adaptive-menu').slinky({
        resize: true,
        title: true
    })

    $('.adaptive-menu-nav-item').click(function () {
        $('.adaptive-menu').removeClass('slinky-menu-custom')
    })

    /*datetime picker*/
    /*$('#newsDateTimePicker').datetimepicker({
        locale: 'ru',
        format: 'L'
    });*/

	/*#Ticket #18098*/
	if (navigator.share && $(window).width() < 768) { // Проверяем поддержку функционала браузера
		button = $('.mobile-share'); // Класс кнопки "поделиться"
		button.show().on('click', function () {
			navigator.share({
			title: $(this).data('title'),
			text: $(this).data('text'),
			url: $(this).data('url'),
			});
			return false;
		});
	}
	/*##*/

$(document).on("scroll", scrolling);

function scrolling () {
    if($("#load-archive").length){
        var yes = $("#load-archive").offset().top;
        var winHeight = $(window).height();
        var s_top = $(window).scrollTop() + winHeight;
        if(s_top > yes){
            $(this).unbind("scroll");
            load_archive();
        }
    }else if($("#load-news").length){
        var yes = $("#load-news").offset().top;
        var winHeight = $(window).height();
        var s_top = $(window).scrollTop() + winHeight;
        if(s_top > yes){
            $(this).unbind("scroll");
            load_news();
        }
    }
};
});

function date_changed(){
    var date = $('#archive_date').val();
    window.history.pushState('1', 'Title', '?date='+date);
    location.reload();
}

function load_archive(){

    $("#load-archive a").css('transform', 'rotate(145deg)').css('transition-duration', '.3s');

    var el_id = 0;
    $.each( $('.page-archive-content-container'), function( key, val ) {
        el_id = $(val).attr('id');
    });

    var ib_id = $('#load_ib_id').val();
		var date = $('#load_date').val();
    var user_access = $('#user_access').val();

    $.post( "/local/ajax/archive.php", { ib_id:ib_id, el_id:el_id, date:date, user_access: user_access })
      .done(function( data ) {

        if(data.length > 50){
            $("#archive_content").append( data );
            $("#load-archive a").css('transform', 'rotate(15deg)');

            $(document).on("scroll", function () {

                var winHeight = $(window).height();
                var s_top = $(window).scrollTop() + winHeight;
                var yes = $("#load-archive").offset().top;

                if(s_top > yes){
                    $(this).unbind("scroll");
                    load_archive();
                }
            });
        }else{
            $(this).unbind("scroll");
            $("#load-archive a").fadeOut('fast');
        }
      });
}

function load_news(){

    $("#load-news a").css('transform', 'rotate(145deg)').css('transition-duration', '.3s');

    var section_code = $('#section_code').val();
    var date_active = $('.date_active').last().val();
    var date_select = $('#date_select').val();
    var showed_ids = $(".showed_ids").serialize()+'&date_select='+date_select+'&date_active='+date_active+'&section_code='+section_code;

    $.ajax({
          type: 'POST',
          url: '/local/ajax/news.php',
          data: showed_ids,
          success: function(data) {

            if(data.length > 50){
                $("#news_content").append( data );

                $("#load-news a").css('transform', 'rotate(15deg)');

                $(document).on("scroll", function () {

                    var winHeight = $(window).height();
                    var s_top = $(window).scrollTop() + winHeight;
                    var yes = $("#load-news").offset().top;

                    if(s_top > yes){
                        $(this).unbind("scroll");
                        load_news();
                    }
                });
            }else{
                $(this).unbind("scroll");
                $("#load-news a").fadeOut('fast');
            }
          }
    });
}
