/* Gallery (slide-on-click, auto-slide-left) */
jQuery.fn.gallSlide = function(_options){
	// defaults options	
	var _options = jQuery.extend({
		duration: 700,
		autoSlide: false,
		slideElement: 1,
		next: '.jcarousel-next, a.btn-next, a.next',
		prev: '.jcarousel-prev, a.btn-prev, a.prev',
		_timer: _options.autoSlide,
		flag: true,
		_t: false,
		runTimer: function(_timerFN){
			_options._t = setInterval(function(){
				if (_options.flag) {
					_options.flag = false;
					_timerFN();
				}
			}, _options._timer);
		},
		stopTimer: function(){
			if(_options._t) clearTimeout(_options._t);
		}
	},_options);
	
	return this.each(function(){
		var _hold = $(this);
		var _speed = _options.duration;
		var _sliderEl = _options.slideElement;
		var _wrap = _hold.find('ul');
		var _el = _hold.find('ul > li');
		var _next = _hold.find(_options.next);
		var _prev = _hold.find(_options.prev);
		var _count = _el.length;
		var _w = _el.outerWidth(true);
		var _active = _count;
		
		var temp = _el.clone();
		_wrap.append(temp);
		temp = _el.clone();
		_wrap.append(temp);
		
		_wrap.css({marginLeft: -(_w * _active) + "px"});
		function scrollEl(){
			_wrap.animate({
				marginLeft: -(_w * _active) + "px"
			}, _speed, function(){
				_options.flag = true;
			});
		}
		timerFN = function (){
			if (_active >= (_count + _count)) {
				_active = _active - _count;
				_wrap.css({marginLeft: -(_w * _active) + "px"});
			}
			_active += _sliderEl;
			scrollEl();
		}
		if (_options._timer) _options.runTimer(timerFN);
		_next.click(function(){
			if (_options.flag){
				_options.flag = false;
				if(_options._t) clearTimeout(_options._t);
				if (_active >= (_count + _count)) {
					_active = _active - _count;
					_wrap.css({marginLeft: -(_w * _active) + "px"});
				}
				_active += _sliderEl;
				scrollEl();
				if (_options._timer) _options.runTimer(timerFN);
			}
			return false;
		});
		_prev.click(function(){
			if (_options.flag) {
				_options.flag = false;
				if (_options._t) 
					clearTimeout(_options._t);
				if (_active < _count) {
					_active += _count;
					_wrap.css({marginLeft: -(_w * _active) + "px"});
				}
				_active = _active - _sliderEl;
				scrollEl();
				if (_options._timer) 
					_options.runTimer(timerFN);
			}
			return false;
		});
	});
}

$(document).ready(function(){
	$('div.jcarousel-container').gallSlide({
		duration: 700,
		autoSlide: 4000,
		slideElement: 3
	});
});

