var livebox, livebox_iframe, breakingInterval, headerBottom, resizeTimer;

$(document).ready(function() {
    if($('.breaking').length>0) {
        $('body').addClass('with-breaking');
        $('.breaking').removeClass('d-none');
    }

    if (livebox_iframe = $('.livebox-wrapper:visible iframe').get(0)) {
        $('.livebox-wrapper:hidden iframe').remove();
    }

    $('.header-modal-open').on('click', function() {
        var modal = $(this).data('modal'), first_input;
        $('.header-modal').removeClass('nav-box-open newsletter-box-open search-box-open registration-box-open').addClass('open').addClass(modal);
        if (first_input = $('.header-modal').find('input:visible').get(0)) {
            $(first_input).focus();
        }
        setTimeout(function() {
            $('.header-modal').addClass('opened');
        }, 300);
        return false;
    });
    $('.header-modal-close').on('click', function() {
        $('.header-modal').removeClass('opened open');
        setTimeout(function() {
            $('.header-modal').removeClass('nav-box-open newsletter-box-open search-box-open registration-box-open');
        }, 300);
        return false;
    });

    $('.form-section input').on('focus', function() {
        var frm_section = $(this).closest('.form-section');
        frm_section.siblings().removeClass('active');
        frm_section.addClass('active');
    });

    $('.img-wrapper.video-wrapper video').mouseover(function(){
        $(this).get(0).play();
    }).mouseout(function(){
        $(this).get(0).pause();
    });

    $('.img-wrapper.gif-wrapper img').each(function () {
        var img_tag = this, wrapper = $(this).closest('.gif-wrapper').get(0);
        if (/.*\.gif/.test(img_tag.src)) {
            var rub = new SuperGif({ gif: img_tag } );
            rub.pause();
            rub.load(function(){
                $(wrapper).addClass('preloaded');
            });
            var gif_tag = rub.get_canvas();
            $(gif_tag).mouseover(function() {
                rub.play();
            }).mouseout(function(){
                rub.pause();
            });
        }
    });

    livebox = $('.livebox.to-fix').get(0);

    $('.video-wrapper, .gif-wrapper').each(function() {
        if (!$(this).find('.img-preloader').length) {
            $(this).addClass('preloaded');
        }
    });
    $('.video-wrapper video').each(function() {
        $(this).on('loadeddata', function () {
            $(this).closest('.video-wrapper').addClass('preloaded');
        });
        if (this.readyState > 3) {
            $(this).trigger('loadeddata');
        }
    });

    $('.embed-responsive iframe').addClass('embed-responsive-item');

    $(document).on('click', '*', function(e) {
        if ($('.header-modal.open').length && !$(e.target).closest('.header-modal').length &&
            !$(e.target).closest('.header-modal-open').length) {
            if ($('.header-modal.open').is('.nav-box')) {
                $('.header-modal.open').addClass('transition');
                setTimeout(function() {
                    $('.header-modal.open').removeClass('open');
                    setTimeout(function() {
                        $('.header-modal.open').removeClass('transition');
                    }, 300);
                }, 1);

            } else {
                $('.header-modal.open').removeClass('open');
            }
        }
    });

    var recent_wrapper, recent_news;
    if ((recent_wrapper = $('.recent-news[data-delayed]').get(0)) &&
        (recent_news = $(recent_wrapper).find('article.delayed').get()) && recent_news.length) {
        var first_delayed = $(recent_wrapper).data('first-delayed');
        var other_delayed = $(recent_wrapper).data('other-delayed');
        setTimeout(function() {
            var new_date = new Date();
            var new_date_str = ((new_date.getHours() < 10) ? '0' : '') + new_date.getHours() + ':' + ((new_date.getMinutes() < 10) ? '0' : '') + new_date.getMinutes();
            var current_news = recent_news.pop();
            //$(current_news).find('.date').html(new_date_str);
            $(current_news).css('display','none').removeClass('delayed').slideDown(300);
            if (recent_news.length) {
                delayed_news(recent_news, other_delayed);
            }
        }, (first_delayed + Math.random() * 5) * 1000);
    }

    var msg = '';
    $('.newsletter-box form').on('submit', function(e) {
        e.preventDefault();
        if ($('.required-check:not(:checked)').length) {
            $('.newsletter-box .msg-wrapper').remove();
            msg = '<div class="msg-wrapper error-msg">Az adatkezelési nyilatkozatot ell kell fogadnia a feliratkozáshoz!</div>';
            $('.newsletter-box .required-check-wrapper').append(msg);
            return false;
        }

        var data = $('#feliratkozas').serialize(),
            url = '?block=Hirlevelek_Feliratkozas&ajax=1';

        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: 'JSON',
            success: function (json) {
                if (json.success) {
                    msg = '<div class="msg-wrapper success-msg">' + json.message + '</div>';
                } else {
                    msg = '<div class="msg-wrapper error-msg">' + json.message + '</div>';
                }
                $('.newsletter-box .msg-wrapper').remove();
                $('.newsletter-box .input-group').append(msg);
            }
        });
    });

    var wrapper_class, video_promo, video_promo_class;
    $('.close-wrapper').on('click', function() {
        wrapper_class = ($(this).hasClass('close-bottom') ? 'bottom-closed' : 'top-closed');
        $('.video-promo').toggleClass(wrapper_class);
        video_promo_class = '';
        if ((video_promo = $('.video-promo').get(0)) && $(video_promo).hasClass('top-closed')) {
            video_promo_class = 'top-closed';
        } else if (video_promo && $(video_promo).hasClass('bottom-closed')) {
            video_promo_class = 'bottom-closed';
        }
        localStorage.setItem('video-promo', video_promo_class);
        return false;
    });
    if (video_promo_class = localStorage.getItem('video-promo')) {
        $('.video-promo').addClass(video_promo_class);
    }
    setTimeout(function() {
        $('.video-promo').addClass('video-promo-transition');
    }, 10);

    countdown_timer(); 
    
    if((!localStorage || localStorage.getItem('adult-page') != 'enabled') && $('body').hasClass("adult-page")) { 
        $('body').append(`<div id="plus18-overlay"></div>
        <div id="plus18-content">
            <h4>18</h4>
            <h3>Figyelem!</h3>
            <p>Az általad megtekinteni kívánt tartalom olyan elemeket tartalmaz, amelyek az Mttv. által rögzített besorolás szerinti V. vagy VI.
            kategóriába tartoznak, és a kiskorúakra káros hatással lehetnek. Ha szeretnéd, hogy az ilyen tartalmakhoz kiskorú ne férhessen hozzá, használj <a href="https://nmhh.hu/cikk/187272/Szuroszoftverek_a_karos_internetes_tartalmak_ellen_gyerekzar" class="link" target="_blank">szűrőprogramot!</a></p>           
            <div class="row">
                <div class="left">
                    <a href="#" class="plus18-btn plus18-agree">Elmúltam 18 éves</a>
                </div>
                <div class="right">
                    <a href="/" class="plus18-btn plus18-disagree">Még nem múltam el 18 éves</a>
                </div>
            </div>
        </div>`);
    
        $('body').on('click', '.plus18-btn.plus18-agree', function(e) {
          e.preventDefault();
          localStorage.setItem('adult-page','enabled');
          $('#plus18-overlay, #plus18-content').remove();
        });
    }
});

function delayed_news(news, delay) {
    setTimeout(function() {
        var new_date = new Date();
        var new_date_str = ((new_date.getHours() < 10) ? '0' : '') + new_date.getHours() + ':' + ((new_date.getMinutes() < 10) ? '0' : '') + new_date.getMinutes();
        var current_news = news.pop();
        //$(current_news).find('.date').html(new_date_str);
        $(current_news).css('display','none').removeClass('delayed').slideDown(300);
        if (news.length) {
            delayed_news(news, delay);
        }
    }, (delay + Math.random() * 10 - 5) * 1000);
}

function window_resize() {
    var ww = $(window).width();

    if (ww < 992 && livebox_iframe && !$('.main-content .livebox-wrapper .embed-responsive iframe').length) {
        $('.main-content .livebox-wrapper .embed-responsive').append(livebox_iframe);
    } else if (ww >= 992 && livebox_iframe && !$('.sidebar .livebox-wrapper .embed-responsive iframe').length) {
        $('.sidebar .livebox-wrapper .embed-responsive').append(livebox_iframe);
    }

    var nav_box;
    if (ww < 992 && (nav_box = $('.nav-box.open').get(0))) {
        $(nav_box).width(ww - $(nav_box).offset().left);
    } else if (nav_box = $('.nav-box.open').get(0)) {
        $(nav_box).removeAttr('style');
    }

    var a_list;
    if (a_list = $('.article-wrapper.article-list').get(0)) {
        $(a_list).find('.img-wrapper.hide').removeClass('hide');
        if (ww > 768) {
            var current_top, row_top = -1, found_img = false, articles_in_row = [];
            $(a_list).find('.img-wrapper.hide').removeClass('hide');
            $(a_list).find('article').each(function () {
                current_top = $(this).offset().top;
                if (current_top != row_top) {
                    if (!found_img && articles_in_row.length) {
                        $(articles_in_row).find('.img-wrapper').addClass('hide');
                    }
                    row_top = current_top;
                    found_img = false;
                    articles_in_row = [];
                }
                articles_in_row.push(this);
                if ($(this).find('.img-wrapper img, .img-wrapper video').length) {
                    found_img = true;
                }
            });
            if (!found_img && articles_in_row.length) {
                $(articles_in_row).find('.img-wrapper').addClass('hide');
            }
        }
    }

    var relateds;
    if (relateds = $('.article-wrapper > .related').get()) {
        $(relateds).removeAttr('style');
        $(relateds).parent().removeAttr('style');
        var margin_bottom = 12;
        if (ww >= 992) {
            $(relateds).each(function() {
                var article = $(this).prev('article').get(0), text_elems, last_text_elem;
                $(this).closest('.has-related').removeClass('moved-related');
                if (article && (text_elems = $(article).find('.text-wrapper > :visible').get()) &&
                    (last_text_elem = text_elems[text_elems.length - 1])) {

                    if ($(last_text_elem).position().top + $(last_text_elem).outerHeight() + $(relateds).height() < $(article).height() - margin_bottom) {
                        // console.log('related', this, 'last_text_elem', last_text_elem, $(last_text_elem).position().top + $(last_text_elem).outerHeight(), ' < ', $(article).height(), ' - 35')
                        $(this).width($(article).find('.text-wrapper').width());
                        $(this).css({
                            position: 'absolute',
                            left: $(last_text_elem).position().left + 'px',
                            top: $(last_text_elem).position().top + $(last_text_elem).outerHeight() + margin_bottom + 'px',
                        });
                        $(this).parent().css('min-height', $(last_text_elem).position().top + $(last_text_elem).outerHeight() + margin_bottom + 20 + $(this).outerHeight() + 'px');
                    } else {
                        $(this).closest('.has-related').addClass('moved-related');
                    }
                }
            });
        }
        $(relateds).css('display', 'block');
    }

    $('.related-articles').each(function() {
        var maxH = 0;
        $(this).find('.carousel-item').removeAttr('style');
        $(this).find('.carousel-item').each(function() {
            if ($(this).outerHeight() > maxH) {
                maxH = $(this).outerHeight();
            }
        });
        $(this).find('.carousel-item').height(maxH);
    });
    
    
    // Breaking animacio
    // Ez meg igy ne menjen ki
/*
    if( $( '.breaking' ).length ) {
        
        var breakingText = $( '.breaking .breaking-text').eq( 0 );
        
        breakingText.removeAttr( 'style' );
        
        var breakingTextWidth = parseFloat( breakingText.width() );
        
        // A sebesseg legyen 50px/sec -> 0.05px/ms
        var animation_speed = 0.05; // px/ms
        var animation_duration = Math.round( breakingTextWidth / animation_speed ); // ms
        
        breakingText.css( {
            '--anim-end' : '-' + breakingTextWidth + 'px',
            '--anim-duration' : animation_duration + 'ms'
        } );
        
    }
*/

    var breaking;
    if (breaking = $('.breaking').get(0)) {
        clearInterval(breakingInterval);
        var breakingText, breakingWrapper, breakingTextWidth;
        breakingText = $(breaking).find('.breaking-text').get(0);
        $(breakingText).removeAttr('style');
        breakingWrapper = $(breakingText).parent().get(0);
        //$(breakingWrapper).css('overflow', 'visible');
        breakingTextWidth = $($(breakingWrapper).find('h3').get(0)).width() + 33;
        $(breakingText).width(breakingTextWidth);
        $(breakingWrapper).removeAttr('style');

        $(breakingText).find('h3:gt(0)').remove();
        $(breakingText).css('left', 0);

        var breakingMargin = $(breakingWrapper).width() - breakingTextWidth;
        if (breakingMargin < 0) {
            breakingInterval = setInterval(function () {
                var left = parseInt($(breakingText).css('left')) - 1;
                $(breakingText).css('left', left + 'px');
                if ($(breakingText).find('h3').length > 1 && left < breakingTextWidth * -1) {
                    left = -2;
                    $(breakingText).css('left', left + 'px');
                    $(breakingText).width(breakingTextWidth);
                    $($(breakingText).find('h3').get(0)).remove();
                } else if ($(breakingText).find('h3').length === 1 && left < breakingMargin) {
                    var breakingClone = $(breakingText).find('h3').clone(false);
                    $(breakingText).find('h3').after(breakingClone);
                    $(breakingText).width(breakingTextWidth * 2);
                }
            }, 20);
        }
    }
}

function countdown_timer() {
    if($(".countdown-wrapper").length) {
        var now = Date.now();
        var countDownDate = new Date($('.count-down-to').html().replace(/-/g, "/")).getTime();

        var x = setInterval(function() {
            var now = Date.now();            
        
            var distance = countDownDate - now;       

            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
            days = days < 10 ? '0' + days : '' + days;
            daysStr = days.toString();
            days_first_digit =daysStr[0];
            days_second_digit =daysStr[1];
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            hours = hours < 10 ? '0' + hours : '' + hours;
            hoursStr = hours.toString();
            hours_first_digit =hoursStr[0];
            hours_second_digit =hoursStr[1];
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            minutes = minutes < 10 ? '0' + minutes : '' + minutes;
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            minutesStr = minutes.toString();
            minutes_first_digit =minutesStr[0];
            minutes_second_digit =minutesStr[1];
            seconds = seconds < 10 ? '0' + seconds : '' + seconds;
            secondsStr = seconds.toString();
            seconds_first_digit =secondsStr[0];
            seconds_second_digit =secondsStr[1];
            $(".days-first-digit").html(days_first_digit);
            $(".days-second-digit").html(days_second_digit);
            $(".hours-first-digit").html(hours_first_digit);
            $(".hours-second-digit").html(hours_second_digit);
            $(".minutes-first-digit").html(minutes_first_digit);
            $(".minutes-second-digit").html(minutes_second_digit);
            $(".seconds-first-digit").html(seconds_first_digit);
            $(".seconds-second-digit").html(seconds_second_digit);

            if (distance < 0) {
                clearInterval(x);
                $(".countdown-wrapper").remove();
            }
        }, 1000);

        countdown_font_resize();
    }
}

function countdown_font_resize() {
    if($(".countdown-wrapper").length) { 
        $(".countdown-wrapper").each(function() {
            if($(this).css("display")=="block") {
                var countdown_box = $(this).find('.countdown-box');
                if($(countdown_box).width() <= 212) { 
                    $(countdown_box).css('font-size', '20px');    
                } else if($(countdown_box).width() <= 272) {
                    $(countdown_box).css('font-size', '25px');
                } else {
                    $(countdown_box).css('font-size', '30px');   
                }
            }
         });
    }
}

$(window).resize(function() {
    if (resizeTimer) {
        clearTimeout(resizeTimer);
    }
    resizeTimer = setTimeout(function() {
        window_resize();
    }, 50);

    if (livebox = $('.livebox.to-fix').get(0)) {
        $(livebox).width($(livebox).parent().width());
        $(window).trigger('scroll');
    }

    countdown_font_resize();
});

$(window).on('scroll', function() {
    var scrolled = $(window).scrollTop();

    if (livebox) {
        var liveboxWrapper = $(livebox).parent().get(0);
        if ($(livebox).not('.fixed') && scrolled > $(liveboxWrapper).offset().top - $('header').outerHeight()) {
            $(liveboxWrapper).height($(livebox).outerHeight() + 20);
            $(livebox).addClass('fixed');
            $(livebox).width($(liveboxWrapper).width());
            $(livebox).css({
                'left': $(liveboxWrapper).offset().left + 'px',
                'top': $('header').outerHeight() + 'px',
            });
        } else if ($(livebox).is('.fixed') && scrolled < $(liveboxWrapper).offset().top - $('header').outerHeight()) {
            $(livebox).removeClass('fixed');
            $(liveboxWrapper).removeAttr('style');
            $(livebox).removeAttr('style');
        }
    }
});

$(window).on('load', function() {
    $(window).trigger('resize');
});
