$(function(){
	initGallery();
})

function initGallery(){
	var _animSpeed = 600;
	$('.gallery').each(function(){
		var _holder = $(this);
		var _frame = $('.gallery-holder', _holder);
		var _slideEl = $('>div>ul', _frame);
		var _slides = $('>li', _slideEl);
		var _prevBtn = $('.prev', _holder);
		var _nextBtn = $('.next', _holder);
		var _active = 0;
		var _step = _frame.width();
		_slides.css('width', _step);
		var _t;

		function resetGall(){
			_step = _frame.width();
			_slides.css('width', _step);
			_slideEl.css('margin-left', -_step * _active)
		}

		function changeSlide(_to){
			_slideEl.animate({
				'margin-left': -_step*_to
			}, _animSpeed, function(){
				_active = _to;
			})
		}

		function nextSlide(){
			_next = _active < _slides.length-1 ? _active+1 : 0;
			changeSlide(_next);
		}

		function prevSlide(){
			_prev = _active > 0 ? _active-1 : _slides.length-1;
			changeSlide(_prev);
		}

		_prevBtn.click(function(){
      clearInterval(timer);
			prevSlide();
			return false;
		})

		_nextBtn.click(function(){
      clearInterval(timer);
			nextSlide();
			return false;
		})

		$(window).resize(function(){
			if (_t) clearTimeout(_t);
			_t = setTimeout(resetGall, 50);
		})
    
    var timer = self.setInterval(function () {
        nextSlide(); 
    }, 6 * 1000);   

	})
}
