jQuery('#banner div.change').show();
jQuery('#banner div.change span.previous').hide();

var n = jQuery('#banner ul li').length;
var width = jQuery('#banner ul li').eq(0).width();
var total = n*width;
var action = true;
var active = false;
var time = 5000;
var direction;

jQuery('#banner ul').css('width',total + 'px');

jQuery('#banner div.change span.previous').click(previous);
jQuery('#banner div.change span.next').click(next);

if (!active) {
	active = !active;
	jQuery('#banner').everyTime(time, 'controlled', function() {
		change();
	});
}

function change()
{
	var newLeft = parseInt(jQuery('#banner ul').css('left'));
	
	if(newLeft == 0)
	{
		direction = 'right';
		next();
	}
	if(newLeft == -total+width)
	{
		direction = 'left';
		previous();
	}
	if(newLeft < 0 && newLeft > -total+width)
	{
		if(direction == 'right')
		{
			next();
		}
		if(direction == 'left')
		{
			previous();
		}
	}
}

function next()
{
	if(action)
	{
		if (active) {
			active = !active;
			jQuery('#banner').stopTime('controlled');
		}
		
		action = false;
		var newLeft = parseInt(jQuery('#banner ul').css('left')) - width;
		
		if(newLeft < 0)
		{
			jQuery('#banner div.change span.previous').show();
		}
		if(newLeft == -total+width)
		{
			jQuery('#banner div.change span.next').hide();
		}
		
		if(newLeft >= -total)
		{
			jQuery('#banner ul').animate(
				{
					left: newLeft
				}, 
				1000, 
				function() {
			    	action = true;
			    	if (!active) {
			    		active = !active;
			    		jQuery('#banner').everyTime(time, 'controlled', function() {
			    			change();
			    		});
			    	}
				}
			);
		}
	}
}

function previous()
{
	if(action)
	{
		if (active) {
			active = !active;
			jQuery('#banner').stopTime('controlled');
		}
		
		action = false;
		var newLeft = parseInt(jQuery('#banner ul').css('left')) + width;
		
		if(newLeft == 0)
		{
			jQuery('#banner div.change span.previous').hide();
		}
		if(newLeft > -total+width)
		{
			jQuery('#banner div.change span.next').show();
		}
		
		if(newLeft <= 0)
		{
			jQuery('#banner ul').animate(
				{
					left: newLeft
				}, 
				1000, 
				function() {
			    	action = true;
			    	if (!active) {
			    		active = !active;
			    		jQuery('#banner').everyTime(time, 'controlled', function() {
			    			change();
			    		});
			    	}
				}
			);
		}
	}
}
