var active;
$(function() {
        
    active = true;
    if($("#produkty div.items div.item").length > 4){
        $("#produkty").everyTime(4000,function(){
            if(active){
                ProductScroll($(this).attr('id'));
            }
        }).mouseover(function(){
            $(this).stopTime();
        }).mouseout(function(){
            $(this).everyTime(4000,function(){
                if(active){
                    ProductScroll($(this).attr('id'));
                }
            });
        });
        
        $("#toNext").click(function(){
            if(active){
                ProductScrollMove("produkty",$("#produkty div.items div.item:eq(1)"));
            }
            return false;
        });
        
        $("#toPrev").click(function(){
            if(active){
                ProductScrollMove("produkty",$("#produkty div.items div.item:eq(0)"),"left");
            }
            return false;
        });
    } else {
        $("#toNext").css({ opacity : 0.3 });
        $("#toPrev").css({ opacity : 0.3 });
    }
});

function ProductScroll(id) {
    var item = $("#" + id + " div.items div.item:eq(0)")
    if(item){
        active = false;
        item.clone().appendTo($("#" + id + " div.items"));
        var moveTo = 0 - parseInt(item.width());
        $("#" + id + " div.items").animate({ left: moveTo + 'px' },1000,function(){
            item.remove();
            active = true;
            $(this).css('left',0);
        });
    }
}

function ProductScrollMove(id,item,direction){
    if(item){
        active = false;
        if(direction == "left"){
            var moveTo = 0;
            var lastItem = $("#" + id + " div.items div.item:last-child");
            lastItem.clone().prependTo($("#" + id + " div.items"));
            $("#" + id + " div.items").css({ left: (0 - item.width()) + 'px'});
            $("#" + id + " div.items").animate({ left: moveTo + 'px' },1000,function(){
                lastItem.remove();
                active = true;
            });
        } else {
            
            var moveTo = 0 - item.position().left;
            if(moveTo != 0){
                var firstItem = $("#" + id + " div.items div.item:first-child");
                firstItem.clone().appendTo($("#" + id + " div.items"));
                $("#" + id + " div.items").animate({ left: moveTo + 'px' },1000,function(){
                    firstItem.remove();
                    active = true;
                    $(this).css('left',0);
                });
            }
        }
    }
}
