/**
 * Фотогалерея-слайдер
 */

$(function(){
    $('#slider_btn_1').css('background', 'url("/images/slider/slider_btn2.png") no-repeat 0 0');
    
    $('div#slider ul').css({
        'width':function(){return $('div#slider ul li').size()*691+'px'}
    });

    var now_num = 1;
    var all = $('div#slider ul li').size();

    if (all > 1) {
        function animate(direction, click)
        {
            if (direction == 'next') {
                $('div#slider ul').animate({marginLeft: '-=691'}, {
                    queue: false,
                    complete: function() {
                        $('div#slider ul li:first-child').appendTo('div#slider ul');
                        $('div#slider ul').css({'margin-left':'0'});
                    }
                });
                if (now_num < all) {
                    now_num++;
                } else {
                    now_num = 1;
                }
            } else if (direction == 'prev') {
                $('div#slider ul li:last-child').prependTo('div#slider ul');
                $('div#slider ul').css({'margin-left':'-691px'});
                $('div#slider ul').animate({marginLeft: '+=691'}, {queue: false});
                if (now_num > 1) {
                    --now_num;
                } else {
                    now_num = all;
                }
            }
            $('#slider_btn_' + now_num).css('background', 'url("/images/slider/slider_btn2.png") no-repeat 0 0');
            $('div[id^=slider_btn_]').not('#slider_btn_' + now_num).css('background', 'url("/images/slider/slider_btn.png") no-repeat 0 0');
            if (click) {
                clearInterval(timeout);
            }
        }

        $('div[id^=slider_btn_]').click(function(){
            var num = $(this).attr('id').substr(11);
            if (num > now_num) {
                while (num > now_num) {
                    animate('next', true);
                }
            }
            if (num < now_num) {
                while (num < now_num) {
                    animate('prev', true);
                }
            }
            
        });

        var timeout = setInterval(function(){animate('next', false);}, 5000);
	}
});

