jQuery(function ($) {
    var $images = $('#slideshow img');
    var $items = $('#slideshow li');
    var index = 0;
    var last = $images.length - 1;
    var timer;
    function slide() {
        $images.eq(index++).fadeOut('slow');
        if (index > last) {
            index = 0;
        }
        $images.eq(index).fadeIn('slow', callback);
    }
    
    function callback() {
    	clearTimeout(timer);
        timer = setTimeout(next, 3000);
    };
    
    $images.eq(index).show();
    callback();
    call = function () {
    	clearTimeout(timer);
    	slide();
   	};
   	function next() {
   		$items.eq(index).removeClass('current');
   		$images.eq(index++).fadeOut('slow');
   		if (index > last) {
            index = 0;
        }
        $items.eq(index).addClass('current');
        $images.eq(index).fadeIn('slow', callback);
	};
	
	function previous() {
		$items.eq(index).removeClass('current');
		$images.eq(index--).fadeOut('slow');
		if (index < 0) {
			index = last;
		}
		$items.eq(index).addClass('current');
		$images.eq(index).fadeIn('slow', callback);
	};
	
	function slideTo(i) {
		$items.eq(index).removeClass('current');
		$images.eq(index).fadeOut('slow');
		index = i;
		$items.eq(index).addClass('current');
		$images.eq(index).fadeIn('slow', callback);
	};
	
	window.next = next;
	window.previous = previous;
	window.slideTo = slideTo;
	
	$('#slideshow a.previous').click(function () {
		previous();
		return false;
	});
	$('#slideshow a.next').click(function () {
		next();
		return false;
	});
	
	function select() {
		slideTo(this.index);
		return false;
	};
	
	$('#slideshow li a').each(function (index) {
		this.index = index;
		$(this).click(select);
	});
	
});
