var currentItem;
var currentItemIndex;
var animating = false;
var timeout;
var interval;

$(function(){

	interval = setInterval(function(){
		
    	var index = currentItemIndex + 1;
        if ($('.links a').size() <= index) {
			index = 0;
		}
		
        var item = $('.list > .item').get(index);

		if (timeout != null) {
			clearTimeout(timeout);
			timeout = null;
		}
		
		animating = true;
        $(currentItem).animate({left: 537}, 500);
        
        timeout = setTimeout(function(){
        	currentItem = item;
        	currentItemIndex = index;
        
			$('.links li').removeClass('active');
	        $('.links a[name="' + currentItemIndex + '"]').parent().addClass('active');
        	
            $(item).animate({left: 0}, 500, function(){
                animating = false;
            });
        }, 700);
	}, 5000);

    currentItem = $('.list > .item').get(0);
    currentItemIndex = 0;
	
    var left = 0;
    $('.list > .item').each(function(){
        $(this).css('left', left + 'px');
        left = 537;
    });

    $('.links a').click(function(){
    	if (interval != null) {
    		clearInterval(interval);
    	}
    	
    	var index = $(this).attr('name');
        var item = $('.list > .item').get(index);

        if (item == currentItem) return;

        $('.links li').removeClass('active');
        $(this).parent().addClass('active');

		if (timeout != null) {
			clearTimeout(timeout);
			timeout = null;
		}

        animating = true;
        $(currentItem).animate({left: 537}, 500);
        
        timeout = setTimeout(function(){
        	currentItem = item;
        	currentItemIndex = index;
        	
            $(item).animate({left: 0}, 500, function(){
                animating = false;
            });
        }, 700);
    });

    var max     = 10;
    var count   = 0;
    $('.links li').each(function(){
        $(this).css('background', 'url("/images/dots/dot' + count + '.png") no-repeat 0px 4px');
        $(this).css('padding-left', '40px');

        count++;
        if (count > max) count = 0;
    });

});
