$(function()
{
    Karusel.init('#karusel');
});

var Karusel =
{
    root:null,
    init: function(root)
    {
        this.root = $(root);
        this.setup();
        this.next();
        this.start();
    },
    setup: function()
    {
        var clz = this;
        clz.root.hover(function(){clz.stop();}, function(){clz.start();});
        this.root.find('.pages a').mouseover
        (
            function()
            {
                var self = $(this);
                var gallery = clz.root.find('div.gallery');
                clz.root.find('div.pages a.active').removeClass('active');
                var key = self.attr('key');
                var div = gallery.find('div.'+key);
                $(this).addClass('active');
                gallery.append(div.hide().fadeIn());
            }
        );
    },
    stop: function()
    {
        if (this.timer)
        {
            clearInterval(this.timer);
            this.timer = null;
        }
    },
    start: function()
    {
        var clz = this;
        this.timer = setInterval(function()
        {
            clz.next();
        }, 3500);
    },
    next: function()
    {
        var active = this.root.find('div.pages a.active');
        
        if (!active.length)
        {
            this.root.find('div.pages a:first').triggerHandler('mouseover');
            return;
        }
        var next = active.next();
        if (next.length == 0)
        {
            next = active.parent().children().first();
        }
        next.triggerHandler('mouseover');
    }
}
