var preloadDistance = 500;
var works = {
    limit : 2,
    feed : 3,
    cur_page : 0,
    stop : false,
    loading : false
}
var tmpl_work;

function createSliders(){
    $.each($(".slider"),function(){
        $(this).find("ul").css("list-style","none");
        $(this).find("ul li").hide();
        $(this).find("ul li:first").show();
        $(this).find("ul li a").click(function(){
            $(this).parent("li").hide();
            next = $(this).parent("li").next("li");
            if(next.index() > -1)next.show();
            else $(this).parents("ul").find("li:first").show();
        });
    });
}

$(document).ready(function(){
    
    $.get('/tmpl/work.html',function(data){tmpl_work=data;
        getMoreHistory();
    });
    
    
    
    $().UItoTop({easingType: 'easeOutQuart'});

    $(window).bind("scroll", function(event) {
        var within_bounds = (($(window).scrollTop()+$(window).height()) >= ($("body").height()-preloadDistance)) ? true : false;
        if (within_bounds) {
            getMoreHistory();
        }
    });

    function getMoreHistory(){
        if(works.stop||works.loading)return;
        works.loading = true;
        $.getJSON('/feed/?page='+works.cur_page+'&json', function(data){
            if(data.processorWork.length){
                $.template( "tmpl_work", tmpl_work );
                result = $.tmpl("tmpl_work", data.processorWork);
                $("#items").append(result);
                //createSliders();
                $(".slider").nivoSlider({effect:'fade',manualAdvance:true,controlNav:false});
                works.cur_page++;
            }else{
                works.stop=true;
            }
            works.loading = false
        });
    }
});
