console.log("Infinite Scroll - Versione " + args_infinite_scroll.current_version);

var IS_HOME_PAGE = args_infinite_scroll.home_page == 1 ? true : false;
var SEMAFORO_CHIAMATA_AJAX = 0;

function isVisibile(selector){

    let top_of_element = jQuery(selector).offset().top;
    let bottom_of_element = jQuery(selector).offset().top + jQuery(selector).outerHeight();
    let bottom_of_screen = jQuery(window).scrollTop() + jQuery(window).innerHeight();
    let top_of_screen = jQuery(window).scrollTop();

    if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        return true;
     } else {
        return false;
     }
}

function caricaNuovoArticolo(){
    SEMAFORO_CHIAMATA_AJAX = 1;


    jQuery.ajax({
        url: args_infinite_scroll.ajax_url,
        type: "POST",
        dataType: "json",
        data: {
            id_articoli: getIdArticoli(),
            ultimo_articolo: getUltimoArticolo(),
            action: 'infinite-scroll-new-post',
        },
        success: function(data){
            jQuery('.post-end').remove();
            jQuery(data.data).insertBefore('#contenitore-related-posts');
            changeUrlAndTitle(jQuery('article')[jQuery('article').length - 1].dataset.url,jQuery(jQuery('article')[jQuery('article').length - 1]).find('h1.single-post-title').text());
            SEMAFORO_CHIAMATA_AJAX = 0;
        }
    });
}

function getUltimoArticolo(){
    return jQuery('article')[jQuery('article').length - 1].dataset.idArticle;
}

function getIdArticoli(){
    let ids = [];

    jQuery('article.single-post').each((i,el) => {
        ids.push(el.dataset.idArticle);
    });

    return ids;
}

jQuery(document).on('scroll',() => {


    scorriProgressbarReadingTime();

    if(!IS_HOME_PAGE && isVisibile('.post-end') && SEMAFORO_CHIAMATA_AJAX == 0 && jQuery('article').length < 7)
        caricaNuovoArticolo();
    
    if(IS_HOME_PAGE && isVisibile('#fine-articoli-home-page') &&  SEMAFORO_CHIAMATA_AJAX == 0)
        caricaNuoviArticoli();
    
    if(!IS_HOME_PAGE) {
        let articoli_visibili = [];

        // Controllo gli articoli a schermo
        jQuery('article').each((i,el) => {
            if(isVisibile(el))
                articoli_visibili.push(el);        
        });
    
        if(articoli_visibili.length == 1){
            changeUrlAndTitle(articoli_visibili[0].dataset.url,jQuery(articoli_visibili[0]).find('h1.single-post-title').text());
        }    
    }
});

function scorriProgressbarReadingTime() {
    let altezza_documento = jQuery(document).height();
    let current_position = jQuery(window).scrollTop();
    let progress = current_position * 100 / altezza_documento;

    if(progress > 10) {
        current_position = jQuery(window).scrollTop() + (jQuery(window).innerHeight() / 2.5);
        progress = current_position * 100 / altezza_documento;
    }
    
    if(progress > 70) {
        current_position = jQuery(window).scrollTop() + (jQuery(window).innerHeight());
        progress = current_position * 100 / altezza_documento;
    }

    jQuery('.reading-time-progressbar .progress').css('width',progress + "%");
}

function getCurrentPage() {
    let classes = jQuery('#fine-articoli-home-page').attr('class');
    let page = classes.split('-')[1];
    return page;
}

function caricaNuoviArticoli() {
    let page = getCurrentPage();
    SEMAFORO_CHIAMATA_AJAX = 1;

    jQuery.ajax({
        url: args_infinite_scroll.ajax_url,
        type: "POST",
        dataType: "json",
        data: {
            page,
            action: 'infinite-scroll-new-posts-in-home',
        },
        success: function(data){
            jQuery('#fine-articoli-home-page').remove();
            jQuery(data.data.html).insertAfter(jQuery('.row.row-articolo').last());

            // Se ci sono nuovi articoli 
            if(!data.data.post_finiti)
                SEMAFORO_CHIAMATA_AJAX = 0;
        }
    });

}

function changeUrlAndTitle(url,title){
    history.pushState({},title,url);
    document.title = title;


    if(!jQuery('#google_gtagjs-js').length != 0)
        return false;

    let analytics_id = jQuery('#google_gtagjs-js').attr('src').split('?id=')[1];

    gtag('config', analytics_id, {
        'page_title' : title,
        'page_path': url.split('/')[3]
    });


}

