$(function(){
	speed = 1000; // Speed animation
	pause = 5000; // Pause (auto slide)

	var nextSlide = function(){
		a = startSlide();
		if(a == $gslider.length-1) a = -1;
		editBg(a+1);
	}
	var thisSlide = function(){
		a = startSlide();
		editBg($(this).index());
	}
	var editBg = function(i){
		$gimg.css('background','url('+$gslider.eq(i).children('img').attr('src')+') no-repeat 0 0');
		$gslider.eq(a).animate({opacity: 'hide'}, speed, function(){
			$gslider.eq(i).show(); endSlide();
		});
	}
	var visibleIndex = function(){
		$gslider.each(function(i){
			if($(this).css('display')!='none'){	a = i;return false;	}
		});	return a;
	}
	var startSlide = function(){
		$gallery.find('.glink').removeClass('glink');
		clearInterval(timer);
		return visibleIndex();
	}
	var endSlide = function(){
		$gallery.find('li').addClass('glink');
		timer = setInterval(nextSlide, pause);
	}
	$gallery = $('.gallery');
	if($gallery.length == 1){
		$gslider = $('a', $gallery);
		$gli	 = $('.glink', $gallery);
		$gimg 	 = $('.gimg', $gallery);
		
		$gslider.hide().eq(0).show();
		$gli.live('click', thisSlide)
		timer = setInterval(nextSlide, pause);
	}
});
