$.fn.gallery = function(_options){
	
	var _obj = this;
	var clicked = false;
	
	options = arrayMerge({
		'speed': 250
	}, _options);
		
	$.extend(this, {
		goto: function(_val){
			if(clicked == false && $('.current .gallery img').length > 1){
				clicked = true;
				$('.current .gallery img:first').stop(true, false).fadeOut(1500, function(){
					$('.current .gallery img:first').before($('.current .gallery img[index=' + _val + ']:first').clone());
					$('.current .gallery img[index=' + _val + ']:last').remove();
					$('.current .gallery img:first').stop(true, false).fadeIn(1500, function(){
						clicked = false;
					});
					$('.current .navigation .nav').removeClass('curr');
					$('.current .navigation .nav:nth-child(' + _obj.getCurrent() + ')').addClass('curr');
				});
			}
		},
		next: function(){
			var next = this.getCurrent() + 1;
			if(this.getCurrent() == this.getTotal()){
				next = 1;
			}
			this.goto(next);
		},
		getCurrent: function(){
			return parseInt($('.current .gallery img:first').attr('index'));
		},
		getTotal: function(){
			return $('.current .gallery img').length;
		}
	});
	
	return this.each(function(){
		var counter = 0;
		$('img', this).each(function(){
			counter++;
			$(this).attr('index', counter);
		});
		$('img:not(:first)', this).hide();
		
		$(this).bind('click', function(){
			_obj.next();
		});
		
		$('.current .nav').live('click', function(){
			_obj.goto($(this).attr('index'));
			$('.current .navigation .nav').removeClass('curr');
			$('.current .navigation .nav:nth-child(' + _obj.getCurrent() + ')').addClass('curr');
		});
		
		var length = $('img', this).length;
		
		$(this).after('<div class="navigation" style="width: ' + length * 15 + 'px"><div class="clear"></div></div>');
		for(var i = 0; i < $('img', this).length; i++){
			$(this).parent('div').children('.navigation').children('.clear').before('<div class="nav" index="' + (i + 1) + '"></div>');
		}
		$(this).parent('div').find('.nav:nth-child(1)').addClass('curr');		
	});
	
	function arrayMerge(_a, _b) {
		if(_a){
			if(_b){
				for(var i in _b){
					_a[i] = _b[i];
				}
			}
			return _a;
		}else{
			return _b;		
		}
	};
}
