jQuery(document).ready(function ($) {

    var css_handles = {
        filter:     '.webien-search-filter',
        resultList: '.webien-search-result',
    };

    var root = document.documentElement;

    var searching = false;

    $('.webien-search-filter a.pt').each(function(){
        var el = $(this);
        el.on('click', function(){

            $('.webien-search-filter a').removeClass('active');
            el.addClass('active');
            $(css_handles.resultList).attr('data-pt', el.attr('data-pt'));

            // First check if the new tab already has content, no need to do a new ajax in that case
            if(!$(css_handles.resultList).find('.result.' + el.attr('data-pt')).is(':empty')){
                $(css_handles.resultList).find('.result').removeClass('active');
                $(css_handles.resultList).find('.result.' + el.attr('data-pt')).addClass('active');
            } else {
                doSearch(el.attr('data-pt'));
            }

            return false;
        });
    });

    function doSearch(pt) {

        var val = $(css_handles.filter).data('search-value');
        var offset = $(css_handles.resultList).find('.result.'+pt+' .item').length;
        var postType = pt;

        if (postType === 'any' && $(css_handles.resultList).data('post-types')) {
            postType = $(css_handles.resultList).data('post-types');
        }

        if(offset >= parseFloat($(css_handles.resultList).find('.result.'+pt).attr('data-total')) ){
            return;
        }

        searching = true;

        // Adjust center of list for loader
        centerListLoader();

        $(css_handles.resultList).addClass('loading');

        $.get({
            url: webien_search_ajax_object.ajax_url,
            data: {
                action: 'webien_relevanssi_search',
                type: 'resultlist',
                value: val,
                post_type: postType,
                quantity: $(css_handles.resultList).data('post-quantity'),
                offset: offset,
                //templates: $(css_handles.resultList).data('post-types-templates'),
                variables: $(css_handles.resultList).data('variables')
            },
            success: function (response) {
                if(!pt){
                    pt = 'any';
                }

                if (response.success === true) {
                    $(css_handles.resultList).removeClass('loading');
                    $(css_handles.resultList).find('.result.active').removeClass('active');
                    $(css_handles.resultList).find('.result.'+pt).addClass('active');

                    display_results(response, val, searching, pt);
                    searching = false;

                }
            },
            error: function () {
            }
        });


    }

    function display_results(response, val, searching, pt){
        if(!searching){
            return;
        };

        if (response.data.posts.length > 0) {
            response.data.posts.forEach(function (post) {
                if(post.link){
                    $(css_handles.resultList).find('.result.'+pt).append('<a href="'+post.link+'" class="item">' + post.html + '</a>');
                } else {
                    $(css_handles.resultList).find('.result.'+pt).append('<span class="item">' + post.html + '</span>');
                }
            });
        }
        centerListLoader();
    }

    function fileExists(pUrl)
    {
        var fileExist = false;
        $.ajax({
            url:pUrl,
            type:'HEAD',
            async:false,
            success: function() {
                fileExist = true;
            },
            error: function() {
                fileExist = false;
            }
        });
        return fileExist;
    }



    // Endless scroll
    function endOfList(elem)
    {
        var currentScroll = $(window).scrollTop();
        var docViewBottom = currentScroll + $(window).height();
        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();
        return (elemBottom < docViewBottom);
    }
    function centerListLoader()
    {
        var currentScroll = $(window).scrollTop();
        var elemTop = $(css_handles.resultList).offset().top;
        var currentCenter = ($(window).height()/2) + currentScroll;
        var elemHeight = $(css_handles.resultList).outerHeight();
        var viewCenter = currentCenter - elemTop;

        if(viewCenter  > elemHeight){
            viewCenter = elemHeight/2;
        }
        viewCenter = Math.floor(viewCenter - 25); // -25 for half of loader height
        // Update css variable
        document.documentElement.style.setProperty('--webien-search-loader-position', 'center ' + viewCenter + 'px');
    }

    $(window).scroll(function() {
        if (!searching && $(css_handles.resultList).length){
            if (endOfList(css_handles.resultList)) {
                var pt = $(css_handles.resultList).find('.result.active').attr('data-pt');
                doSearch(pt);
            }
        }
    });

});
