var deeb = {

    categoryHandler: function(lis)
    {
        lis.each(function(i, el){
            var $this = $(el)
            $this.find('a:first').click(function(){
                if ($(el).hasClass('selected'))
                {
                    $(el).removeClass('selected');
                } else {
                    $(el).addClass('selected');
                }
                return false;
            })
        })
    }

}

function galleryImages(el, nextel, prevel)
{
    var current = 0;
    var speed = 4000;
    var next = 1;
    var transitionSpeed = 1000;

    function handleClass(current, other, cycle)
    {
        $(el[current]).removeClass("active");
        $(el[other]).addClass("active");

        if (cycle == true) return false;

        clearInterval(interval);
        
        $(el[current]).stop().animate({ opacity: 0 }, function() {
            $(this).hide();
        });
        $(el[other]).stop().css({ display: "block", opacity: 0 }).animate({ opacity: 1 });
    }
    
    function cycleImages()
    {
        handleClass(current, next, true);
        $(el[current]).fadeOut(transitionSpeed);
        $(el[next]).fadeIn(transitionSpeed, function() {
            current = current + 1;
            if ( current > el.length - 1 ) current = 0;
            next = next + 1;
            if ( next > el.length - 1 ) next = 0;
        });
    }

    var interval = setInterval(cycleImages, speed);

    for (var i=0; i<el.length; i++)
    {
        if (i == 0) $(el[i]).addClass('active');
        if (i !== 0) $(el[i]).hide();
    }
    
    nextel.click(function(){
        next = current + 1;
        if ( next > el.length - 1 ) next = 0;
        handleClass(current, next, false);
        current = next;
        return false;
    });
    
    prevel.click(function(){
        prev = current - 1;
        if ( prev < 0 ) prev = el.length - 1;
        handleClass(current, prev, false);
        current = prev;
        return false;
    });
    
}

$(document).ready(function() {
    $("a.zoom").fancybox();
    deeb.categoryHandler($('#primary-categories>li'));
    galleryImages($('#gallery-images li'), $('#gallery-next'), $('#gallery-prev'))
});

