﻿$(document).ready(function() {
    $('#gallery').each(function() {
        var slider = $(this).find('ul.slider');                
        var count = slider.find('li').size();
        var size = slider.find('li').width();
        
        var switcher = $(this).find('.switcher ul li a:not(.nav)');
        var nav = $(this).find('.switcher ul li a.nav');
                
        var slide = function(obj, ind, leftmargin, pos, anim, timeout) {
            if(pos > count-1)
                pos = 0;
            if(pos <0)
                pos = count-1;
                
            ind.removeClass('active');
            ind.eq(pos).addClass('active');            
                        
            obj.stop().animate({                
                left: '-' + (leftmargin * pos),                
              }, anim, function() {
                $.doTimeout('slide-gallery' , timeout, function(){
                    if(timeout > -1)
                        slide(slider, switcher, size, (pos+1), anim, timeout);
                 });
              });
        };
        
        switcher.each(function(index)
        {
            $(this).click(function(){
                $.doTimeout('slide-gallery');
                slide(slider, switcher, size, index, 1500, -1);
            });
        });
        
        nav.each(function(index)
        {
            $(this).click(function(){
                $.doTimeout('slide-gallery');
                var pos = 0;
                switcher.each(function(index){
                    if($(this).hasClass('active'))
                        pos = index;
                });
                
                pos = pos + ($(this).hasClass('prev') ? -1:1);
                slide(slider, switcher, size, pos, 1500, -1);
            });
        });
        
        slide(slider, switcher, size, 0, 1500, 4000);

    });
});
