$(document).ready(function(){
	initGallery();
});

function initGallery() {
	var _galleryEl = $("div.gallery div.gallery-holder ul li");
	var _galEl = "li";
	var _linkNext = $("ul.control .next a");
	var _linkPrev = $("ul.control .prev a");
	var _duration = 500;
	var _timeSwitching = 5000;
	
	var _numElActive = false;
	var _n = false;
	
	$(_galleryEl).not(".active").css('display','none');
	currentIMG();
		
	$(_linkNext).click(function(){
		if ($(_galleryEl).filter(".active").next().is(_galEl)) {
			$(_galleryEl).filter(".active").next().addClass("next");
		} else {
			$(_galleryEl).eq(0).addClass("next");
		}
		fadeElement();
		clearTimeout(_timer);
		_timer = setTimeout(function() {nextEl()},_timeSwitching);
		return false;
	});
	
	$(_linkPrev).click(function(){
		if ($(_galleryEl).filter(".active").prev().is(_galEl)) {
			$(_galleryEl).filter(".active").prev().addClass("next");
		} else {
			$(_galleryEl).filter(":last-child").addClass("next");
		}
		fadeElement();
		clearTimeout(_timer);
		_timer = setTimeout(function() {nextEl()},_timeSwitching);
		return false;
	});
	
	_timer = setTimeout(function() {nextEl()},_timeSwitching);
	
	function nextEl(){
		if ($(_galleryEl).filter(".active").next().is(_galEl)) {
			$(_galleryEl).filter(".active").next().addClass("next");
		} else {
			$(_galleryEl).eq(0).addClass("next");
		}
		fadeElement();
		_timer = setTimeout(function() {nextEl()},_timeSwitching);
	}
	function fadeElement(){
		$(_galleryEl).filter(".active").fadeOut(_duration).removeClass("active");
		$(_galleryEl).filter(".next").fadeIn(_duration).addClass("active").removeClass("next");
		currentIMG();
	}
	function currentIMG () {
		var _all = _galleryEl.length;
		var _current = _galleryEl.index(_galleryEl.filter('.active'));
		$('span.all-img').html(_all);
		$('span.current-img').html(_current+1);
	}
}
